/*

 V6 READY

#################################################################
 DO NOT MODIFY THIS FILE UNDER ANY CIRCUMSTANCES
#################################################################

 Copyright Intersoft Systems Limited. All Rights Reserved

 Widget User Interface utilities v1.63 (21-Oct-2024)

 NOTE
 ----
 This contains limited UI functionality. Use external
 libraries such as Bootstrap if more comprehensive functionality
 is required.

 Sub-Objects
 -----------
 * Charts
  * ApexCharts
   * Chart(elementId, options)
   * GridVisualiser(elementId, grid, options)
  
 * Forms
  * ShowAccountSchedule
  * ShowCompanyLookup
  * ShowDataTableViewer
  * ShowHtml
  * ShowHtmlWidgetModal
  * ShowUrl (currently internal use only - website)
  * ShowRangeLookupFromDatabase
  * ShowRangeLookupFromStandardRange

 Creatable Controls and Objects
 ------------------------------
 * AccountIncomingPaymentDetails(elementId, options)
 * AccountOutgoingPaymentDetails(elementId, options)
 * AccountFinancial(elementId, options)
 * AddressDetails(elementId, options)
 * BankingDetails(elementId, options)
 * Button(elementId, options)
 * ButtonList(elementId, options)
 * ButtonStrip(elementId, options)
 * Calendar(elementId, options)
 * CheckBox(elementId, options)
 * CheckList(elementId, options)
 * ColourChooserComboBox(elementId, options)
 * ComboBox(elementId, options)
 * CompareItemsGrid(elementId, options)
 * DateBox(elementId, options)
 * DateTimeZone(elementId, options)
 * DateCycleComboBox(elementId, options)
 * DashboardLayout(elementId, options)
 * DBCombo(elementId, options)
 * DocumentManagerComboBox(e, options)
 * DropdownPanel(elementId, options) - NOTE: Internal use only at present
 * ExpiryDate(elementId, options)
 * FileUpload(elementId, options)
 * Form(elementId, options)
 * Grid(elementId, options)
 * GroupingList(elementId, options)
 * HtmlEditor(elementId, options)
 * IconComboBox(e, options)
 * InformationListComboBox(elementId, options)
 * Modal(options)
 * NumberBox(elementId, options)
 * ParametersHost(elementId, options) - stub only, fully implemented in widget_parametershost.js
 * PermissionKeyComboBox(elementId, options)
 * PreviewPane(elementId, options)
 * PromptUpdateList(options)
 * RadioButton(elementId, options)
 * RadioButtonList(elementId, options)
 * RangeSlider(elementId, options)
 * Repeater(elementId, options)
 * StyleAsModal(elementId, options)
 * Tabs(elementId, options)
 * TextBox(elementId, options)
 * TimeBox(elementId, options)

 General
 -------
 * Block ([message])
 * BookmarkToggleTabs(tabs, recordType, pk, code, description)
 * ClearTextSelection
 * DirtyTrackingEnabled(value)
 * DisableControlStyling(value)
 * Unblock
 * GetInputDate(message, [options], [callback]])
 * GetInputDateTime(message, [options], [callback]])
 * HtmlNamedColourToRgb(namedColour)
 * HtmlEncode(value, [makeSpacesNonBreaking])
 * MsgBoxAlert(message, [options], [callback])
 * MsgBoxConfirm(message, [options], [okCallback], [cancelCallback])
 * MsgBoxConfirmDelete(message, [options], [okCallback], [cancelCallback])
 * MsgBoxConfirmList(message, list, [options], [okCallback], [cancelCallback])
 * MsgBoxInfo(message, [options], [callback])
 * MsgBoxList(message, list, [options], [listCallback])
 * OrderElements(containerElement, tagName, orderAttributeName, desc)
 * ScrollToTop(elementId)
 * SelectDocumentManagerFile(sourceType, sourceId, options, callback)
 * SelectFlagColour(list, options, callback)
 * SelectResource(options, callback)
 * ShowNotification(type, message, details, title, icon)
 * ValidateContainer(container)
 * LoadStyle(style, [options])
 * Evaluate(elementId, [options])
 * VisualiseControlChanged(ctl)

 Addressing
 ----------
 * InitialiseAddressAutoComplete

 <SELECT> element
 ----------------
 * DDListFromCsv(e, csvString, [alwaysIncludeValue])
 * DDListFromArray(e, array, [alwaysIncludeValue])
 * DDListFromCollection(e, array, displayProperty, [valueProperty], [alwaysIncludeValue])
 * DDListAdd(e, item)

 <TABLE> element
 ---------------
 * TableAddRowsFromCollection(e, array, [fieldList], [formatCallback])
 ################################################################
*/

console.log("Loading widget_ui.js (extension)");

// ==
// UI
// ==
var __WidgetUI = function (widget) {
  // Debug
  var mDisableProxyControls = false; // Set to true to prevent controls being created in finCC  for debugging

  var mBlockElement = null;
  var mBlockTime = new Date();
  var mDirtyTrackingEnabled = false;
  var mDirtyTrackingTimer = null;
  var mDisableControlStyling = false;
  var mHtmlEncodeElement = null;
  var mFormDisabled = false;
  var mFormDisableOverlay;

  var mAddressingGoogleMaps3Initialising = false;
  var mAddressingGoogleMaps3Initialised = false;
  var mAddressingGoogleMaps3CallbackList = [];

  var mIsSmallMobileBrowser = false;
  var mSupportsStickyHeaders = true;

  var mGridListCache = {};
  var mInformationListCache = {};
  var mPermissionKeyListCache = null;
  var mPermissionKeyListFetching = false;

  var mModalCount = 0;
  var mModalOpenCount = 0;
  var mModalStack = [];

  var mThemeBackgroundColour = "orange";
  var mThemeContrastColour = "navy";
  var mThemeContrastColourActionsForm = "navy";
  var mCompactMode = false;

  // ===========================================
  // finPOWER Connect Cloud $Runtime substitutes
  // ===========================================
  window.Runtime_CombineDateTimeUtc = function CombineDateTimeUtc(d, t) { if (d) { if (t) { d = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds())); } else { d = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate())); } return d; } else { return null; } };
  window.Runtime_IsMobileBrowser = false; // Set later
  window.Runtime_IsPlatformIOS = false; // Set later
  window.Runtime_ParseDate = widget.ParseDate;
  window.Runtime_FormatCurrency = widget.FormatCurrency;
  window.Runtime_FormatDate = widget.FormatDateInternal;
  window.Runtime_ParseJsonDate = function (s) { if (s) { return new Date(s); } else { return null; } };
  window.Runtime_FormatNumber = widget.FormatNumber;
  window.Runtime_ParseNumber = widget.ParseNumber;
  window.Runtime_GetMonthName = function (index, short) { var a = []; if (!short) { a = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; } else { a = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; } try { return a[index]; } catch (e) { if (short) return "Un"; else return "Unknown"; } };
  window.Runtime_GetDayOfWeekName = function (index, short) { var a = []; if (!short) { a = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; } else { a = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; } try { return a[index]; } catch (e) { if (short) return "Un"; else return "Unknown"; } };
  window.Runtime_GetString = function (e, trim) { if (typeof trim == "undefined") trim = true; if (typeof e == "string") e = $("#" + e); if (e) { try { var s = $(e).val(); if (trim) s = RTrim(s); return s; } catch (e) { return ""; } } else { return ""; } };
  window.Runtime_StringArrayAddUnique = function (array, s) { if (!s) s = ""; else s += ""; var s2 = s.toUpperCase(); var found = false; for (var i = 0; i < array.length; i++) { if (array[i].toUpperCase() == s2) { found = true; break; } } if (!found) array.push(s); };
  window.Runtime_WebRoot = "../";

  // Apply a class to the body if hosting in certain contexts (so CSS etc can be adjusted)
  var mDesktop = false;
  switch (widget.GetHostingContext()) {
    case "WebExternal":
    case "WebInternal":
      break;
    default:
      mDesktop = true;
      $("body").addClass("is-desktop");
      break;
  }

  // Attempt to detect theme information if running under finPOWER Connect Cloud
  if (widget.GetHostingContext() == "WebInternal") {
    try {
      var div = window.parent.document.getElementById("themecolourtester");
      if (div) {
        // Determine colours
        div = $(div);
        mThemeContrastColour = div.css("background-color");
        mThemeContrastColourActionsForm = div.css("border-top-color");
        mThemeBackgroundColour = div.css("border-left-color");

        // Compact mode?
        var els = window.parent.document.getElementsByTagName("html");
        if (els.length != 0) {
          mCompactMode = $(els[0]).hasClass("is-compact");
          if (mCompactMode) {
            $("html").addClass("is-compact");
            console.log("widget_ui: Compact Mode applied.");
          }
        }

        // Update style sheet
        $("head").append("<style type='text/css'></style>");
        var newStyleElement = $("head").children(":last");
        newStyleElement.html(".is-widget-content footer { border-top-color: " + mThemeContrastColour + " !important; }\n\n" +
          ".is-modal .is-modal-title { background-color: " + mThemeContrastColour + " !important; color: white !important; }\n\n" +
          ".is-modal .is-modal-close,.is-modal.is-modal-minimise,.is-modal.is-modal-open-window { color:rgba(255,255,255,0.6) !important; }\n\n" +
          ".is-modal .is-modal-close:hover,.is-modal.is-modal-minimise:hover,.is-modal.is-modal-open-window:hover { color:rgba(255,255,255,1) !important; }\n\n" +
          "div.help h1,div.help h2,div.help h3 {color:" + mThemeBackgroundColour + " !important; }\n\n" +
          "table.is-grid tr.group-header {color:" + mThemeContrastColour + " !important; }\n\n" +
          "button.is-button.checked {background-color:" + mThemeContrastColour + " !important; }\n\n");
      }
    }
    catch (ex) {
      // Ignore
    }
  }

  // Attempt to detect Web Root and other settings if running under finPOWER Connect Cloud
  if (widget.GetHostingContext() == "WebInternal") {
    try {
      Runtime_WebRoot = window.parent.$Runtime.WebRoot();
      Runtime_IsMobileBrowser = window.parent.$Runtime.IsMobileBrowser();
      Runtime_IsPlatformIOS = window.parent.$Runtime.IsPlatformIOS();
    }
    catch (ex) {
      // Ignore
    }
  }

  // Other hosting context specific tweaks
  switch (widget.GetHostingContext()) {
    case "HtmlViewer":
    case "PageSet":
      // Running inside finPOWER Connect, Web Browser control may need a few style tweaks
      break;
  }

  // Detect Mobile Web Browser etc
  if (screen.width <= 640 || screen.height <= 640) {
    mIsSmallMobileBrowser = true;
  }



  // jQuery Initialise
  $(function () {
    //// Mutation Observers
    //// https://stackoverflow.com/questions/10415400/jquery-detecting-div-of-certain-class-has-been-added-to-dom
    //var o = new MutationObserver(function (mutations) {
    //  mutations.forEach(function (mutation) {
    //    window.alert($("*[icon]", mutation.target).length);
    //    // Icons
    //    //var els = $("*[icon]", mutation.target);
    //    //if (els.length != 0 ) ApplyIcons();
    //    //if (mutation.addedNodes && mutation.addedNodes.length != 0) {
    //    //  //window.alert("addedNodes: " + $(mutation.addedNodes[0]).html());
    //    //  ApplyIcons($("*[icon]", mutation.addedNodes));
    //    //}
    //  });
    //});
    //o.observe(document.body, { attributes: true, childList: true, characterData: true, subtree: true });

    // Startup
    ApplyIcons($("*[icon]"));

    // Global handlers
    $(document.body).bind("keydown", function (e) {
      // Escape key
      if (e.keyCode == 27) {
        // Close top modal?
        if (mModalStack.length > 0) {
          var m = mModalStack[mModalStack.length - 1];
          if (m.CloseOnEscape()) m.Close();
        }
      }
    });

    // Enable Dirty Tracking by default?
    // NOTE: Not for Portals (J033787)
    if (window.Form_IsDirty && !window.portal) {
      DirtyTrackingEnabled(true);
    }
  });

  // ==============================
  // PRIVATE: Trigger Tab Key Press
  // ==============================
  function TriggerTab(e) {
    var els = $("input,button,textarea,select,label.is-checkbox");
    var found = false;
    for (var i = 0; i < els.length; i++) {
      var el = els[i];
      if (el === e[0]) {
        found = true;
      }
      else if (found) {
        var elj = $(el);
        if (elj.is(":visible")) {
          var skip = false;
          if (el.tagName == "BUTTON") {
            if (elj.attr("tabIndex") == -1) skip = true;
            if (elj.attr("disabled") == "disabled") skip = true;
          }
          else if (elj.attr("for") == e.prop("id")) {
            // Skip checkbox's own label
            skip = true;
          }

          if (!skip) {
            if (elj.hasClass("is-checkbox")) {
              // Checkbox (focus associated label)
              var chk = $("#" + elj.attr("for"));
              chk.focus();
            }
            else {
              // Other
              elj.focus();
              elj.select();
            }
            break;
          }
        }
      }
    }
  }

  // ------------------------------------------------------
  // PRIVATE: Focus on the first Input field in a container
  // ------------------------------------------------------
  function FocusFirst(container) {
    // Get input controls in the container
    var ctrls = $("input,select,textarea,div[tabindex=-1],span[tabindex=0]", container);

    // Exclude disabled, read-only and invisible elements
    for (var i = 0; i < ctrls.length; i++) {
      var c = $(ctrls[i]);
      var include = true;

      if (include && c.prop("disabled")) include = false;
      if (include && c.is("[readonly]")) {
        if (c.hasClass("fetchingdata")) {
          // Ignore since this is a DBCombo that is only read-only because it is fetching data!
        }
        else {
          include = false;
        }
      }
      if (include && !c.is(":visible")) {
        if (c.attr("type") == "checkbox") {
          // Checkboxes are always hidden so we must look at the actual control's label
          var chkid = c.prop("id");
          var chklbl = $("label[for='" + chkid + "']");
          if (chklbl.length == 1 && !chklbl.is(":visible")) {
            include = false;
          }
        }
        else {
          include = false;
        }
      }

      if (include) {
        c.focus().select();
        break;
      }
    }
  }

  // ============================================================
  // PRIVATE: Handle a jQuery ContextMenu Event
  //
  // NOTE: Required since iOS does not support the standard event
  // ============================================================
  function HandleContextMenuEvent(e, callback) {
    if (Runtime_IsPlatformIOS) {
      // iOS (simulate long press)
      e.off("touchstart.contextmenu");

      var t = null;
      var poppped = false;
      e.on("touchstart.contextmenu", function (touchEvents) {
        if (touchEvents.target === e[0]) {
          popped = false;
          t = window.setTimeout(function () {
            window.clearTimeout(t);
            t = null;
            popped = true;
            var touch = touchEvents.originalEvent.touches[0];
            var ev = { clientX: touch.pageX, clientY: touch.pageY };
            callback(ev);
          }, 750);
        }
      });

      e.on("touchend.contextmenu", function (touchEvents) {
        if (touchEvents.target === e[0]) {
          if (popped) {
            touchEvents.preventDefault();
            touchEvents.stopPropagation();
          }
        }
        window.clearTimeout(t);
        t = null;
      });
    }
    else {
      // General
      e.on("contextmenu", callback);
    }
  }

  // =============================
  // PRIVATE: Normalise Menu Items
  // =============================
  function Define_Normalise(items) {
    // Menu Item defaults
    var MenuItemDefaults = {
      ItemId: "",
      ItemType: "Normal",
      Caption: "",
      Icon: "",         // An Icon Resource Id
      IconUrl: "",      // An Icon URL
      IconClass: "",    // A CSS Class representing an Icon
      MenuItems: [],
      Enabled: true,
      Visible: true,
      AllowMultiInstance: false,
      System: false,
      Indent: false
    };

    for (var i = 0; i < items.length; i++) {
      items[i] = $.extend({}, MenuItemDefaults, items[i]);

      // Sub-items
      if (items[i].MenuItems && items[i].MenuItems.length != 0) {
        // Recurse
        Define_Normalise(items[i].MenuItems);
      }
    }
  }

  // ===================
  // PUBLIC: Apply Icons
  // ===================
  function ApplyIcons(elements) {
    if (!elements) return;

    // Class
    elements.addClass("icon");

    // Background Image
    for (var i = 0; i < elements.length; i++) {
      var el = $(elements[i]);
      var icon = $(elements[i]).attr("icon");
      if (icon) {
        var iconsize = $(elements[i]).attr("iconsize");
        if (!iconsize) iconsize = 16;
        var iconUrl = widget.GetIconUrl(icon, iconsize);
        iconUrl = iconUrl.replace(/\\/g, "/");  // Backslash to forward slash when running from local file system
        el.css("background-image", "url(" + iconUrl + ")");
      }
      else {
        el.removeClass("icon");
        el.css("background-image", "");
      }
    }
  }

  // =============================
  // PUBLIC: Clear text selections
  // =============================
  function ClearTextSelection() {
    var sel = window.getSelection ? window.getSelection() : document.selection;
    if (sel) {
      if (sel.removeAllRanges) {
        sel.removeAllRanges();
      }
      else if (sel.empty) {
        sel.empty();
      }
    }
  }

  // ====================
  // PUBLIC: Block the UI
  // ====================
  function Block(message) {
    if (!message) message = "";

    // Create element?
    if (mBlockElement) {
      // Update message
      $("label", mBlockElement).text(HtmlEncode(message));
    }
    else {
      mBlockElement = $("<div class='is-wait-block'><div class='is-wait'><div class='is-wait1'></div><div class='is-wait2'></div><div class='is-wait3'></div></div><label>" + HtmlEncode(message) + "</label></div>");
      $("body").append(mBlockElement);
    }

    // Show
    mBlockElement.fadeIn("fast");

    // Record block time
    mBlockTime = new Date();

    // Indicate modal is blocked
    var modal = window.__modal;
    if (modal && modal.ModalElement) {
      modal.ModalElement().addClass("is-blocked");
    }
  }

  // ======================
  // PUBLIC: Unblock the UI
  // ======================
  function Unblock() {
    if (mBlockElement) {
      // Remove
      var now = new Date();
      var ms = now - mBlockTime;
      var oldBlockTime = mBlockTime;
      if (ms < 750) {
        // Delay unblock to prevent flashing on fast requests
        var t = window.setTimeout(function () {
          window.clearTimeout(t);
          t = null;

          if (oldBlockTime == mBlockTime || !mBlockElement) {
            if (mBlockElement) mBlockElement.remove();
            mBlockElement = null;
          }
          else {
            // Reblocked so ignore
          }
        }, 750 - ms);
      }
      else {
        if (mBlockElement) mBlockElement.remove();
        mBlockElement = null;
      }
    }

    // Indicate modal is no longer blocked
    var modal = window.__modal;
    if (modal && modal.ModalElement) {
      modal.ModalElement().removeClass("is-blocked");
    }
  }

  // ===================================================
  // PUBLIC: Builds UI Progress for Background Processes
  // ===================================================
  function BuildBackgroundProcessProgress(divProgress, clear, backgroundProcessStatus, lastEventId) {
    // Clean input
    if (clear === undefined) clear = false;

    // Exit if Parameters invalid
    if (!divProgress) return;

    // Build Progress
    if (clear) {
      divProgress.children().remove();
      divProgress.append("<div class='event event-wait'>Please wait...</div>");
    }
    else if (backgroundProcessStatus) {
      // Events
      // NOTE: 'Pending' means the background process has yet to start (i.e., be picked up by Web Services)
      if (backgroundProcessStatus.Status != "Pending" && backgroundProcessStatus.StatusEvents) {
        for (var i = 0; i < backgroundProcessStatus.StatusEvents.length; i++) {
          var item = backgroundProcessStatus.StatusEvents[i];

          // Append
          var ev = $("<div class='event'></div>");
          var descriptionDetailsContainer = $("<div class='description-details-container'></div>");
          var descriptionImage = $("<div class='description-image'></div>");
          var descriptionDetails = $("<div class='description-details'></div>");
          var timing = $("<span class='event-timings'></span>");
          var description = $("<span></span>");

          // Timing - Support old runs prior to date display implementation
          if (item.DatabaseDateForDisplay) {
            timing.html(widget.UI.HtmlEncode(item.DatabaseDateForDisplay));
            ev.append(timing);
          }

          // Description
          description.append(widget.UI.HtmlEncode(item.Description, true));

          // Details
          descriptionDetailsContainer.addClass(item.WarningLevel);
          descriptionDetails.append(description);
          if (item.Details) {
            var dt = $("<div class='details'></div>");
            dt.html(widget.UI.HtmlEncode(item.Details));
            descriptionDetails.append(dt);

            // Image
            switch (item.WarningLevel) {
              case "Medium":
              case "High":
              case "Critical":
                descriptionImage.addClass("show-warning-image");
                break;
            }            
            descriptionDetailsContainer.append(descriptionImage);
          }

          descriptionDetailsContainer.append(descriptionDetails);
          ev.append(descriptionDetailsContainer);
          divProgress.append(ev);

          // Scroll to bottom to show new events
          divProgress.scrollTop(divProgress[0].scrollHeight);

          // Ensure we only fetch later events
          lastEventId = item.EventId;
        }
      }

      // Failed Error
      if (backgroundProcessStatus.FailedErrorMessage) {
        var pd = $("<div class='error-item'></div>");
        var failImage = $("<div class='error-item-image'></div>");
        var failError = $("<div class='error-item-text'></div>");

        failError.text(backgroundProcessStatus.FailedErrorMessage);

        pd.append(failImage);
        pd.append(failError);
        divProgress.append(pd);
      }
    }

    return lastEventId;
  }

  // =================================
  // PUBLIC: Count of Open Modal forms
  // =================================
  function ModalOpenCount() {
    return mModalOpenCount;
  }

  // =======================================================================
  // PUBLIC: Style an element as if it is a Modal form, even though it isn't
  // =======================================================================
  function StyleAsModal(e, options) {
    // Extend options with defaults
    var o = $.extend({},
      {
        title: null,
        animate: true,
        showClose: false,
        hideOnClose: true,
        tool: false, // Tool windows are styles differently, more like old-style MS Office draggable toolbars
      },
      options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.StyleAsModal: Element '" + id + "' not found.");
      return;
    }

    // Style
    e.addClass("is-modal");
    if (o.animate) e.css("animation", "pop 0.2s");
    if (o.tool) e.addClass("tool");

    // Wrap body
    e.wrapInner("<div class='is-modal-body'></div>");

    // Title
    if (o.title) {
      $("div.is-modal-body", e).before("<div class='is-modal-title'>" + HtmlEncode(o.title) + "<div class='is-modal-title-buttons'><div class='is-modal-close is-symbol-close' title='Close'></div></div></div>");

      // Close button
      var cb = $("div.is-modal-title-buttons > div.is-modal-close", e);
      if (o.showClose) {
        cb.on("click", function () {
          if (o.hideOnClose) {
            e.hide();
          }
        });
      }
      else {
        cb.hide();
      }
    }

  }

  // ====================================
  // PUBLIC: Get a Modal from its modalId
  // ====================================
  function GetModalById(modalId) {
    // Find Modal
    for (var i = 0; i < mModalStack.length; i++) {
      var modal = mModalStack[i];
      if (modal.ModalId() == modalId) return modal;
    }

    return null;
  }

  // ==========================================
  // PUBLIC: Add a text item to a dropdown list
  // ==========================================
  function DDListAdd(e, item) {
    var e = GetElement(e);

    if (e) {
      var opt = $("<option></option>");
      opt.text(item);
      e.append(opt);
    }
  }

  // ======================================================
  // PUBLIC: Set the list of a Select Element from an Array
  // ======================================================
  function DDListFromArray(e, array, alwaysIncludeValue) {
    var e = GetElement(e);

    if (e) {
      // Clear existing
      e.children().remove();

      // Add new
      var alwaysIncludeItemFound = false;
      for (var i = 0; i < array.length; i++) {
        var opt = $("<option></option>");
        opt.attr("value", array[i]);
        opt.text(array[i]);
        e.append(opt);

        if (alwaysIncludeValue && !alwaysIncludeItemFound && array[i] == alwaysIncludeValue) {
          alwaysIncludeItemFound = true;
        }
      }

      // Ensure 'Always Include Value' exists in list
      if (alwaysIncludeValue && !alwaysIncludeItemFound) {
        var opt = $("<option></option>");
        opt.attr("value", alwaysIncludeValue);
        opt.text(alwaysIncludeValue);
        e.append(opt);
      }
    }
  }

  // =====================================================
  // PUBLIC: Set the list of a Select Element a Collection
  // =====================================================
  function DDListFromCollection(e, array, displayProperty, valueProperty) {
    var e = GetElement(e);

    if (e) {
      // Clear existing
      e.children().remove();

      // Add new
      for (var i = 0; i < array.length; i++) {
        var item = array[i];
        var opt = $("<option></option>");
        opt.text(item[displayProperty]);
        if (valueProperty) opt.attr("value", item[valueProperty]);
        e.append(opt);
      }
    }
  }

  // ==========================================================
  // PUBLIC: Set the list of a Select Element from a CSV String
  // ==========================================================
  function DDListFromCsv(e, csvString, alwaysIncludeValue) {
    csvString = "" + csvString;
    DDListFromArray(e, csvString.split(","), alwaysIncludeValue);
  }

  // ========================================
  // PUBLIC: Disable Control Styling property
  // ========================================
  function DisableControlStyling(value) {
    if (value === undefined) {
      // Get
      return mDisableControlStyling;
    }
    else {
      // Set
      mDisableControlStyling = (value == true);
    }
  }

  // ====================================================
  // FRIEND: Get jQuery Element from Id or jQuery element
  // ====================================================
  function GetElement(e) {
    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      e = $("#" + e);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget.UI: Element '" + id + "' not found.");
      return null;
    }
    return $(el[0]);
  }

  // ===================
  // PUBLIC: HTML Encode
  // ===================
  function HtmlEncode(value, makeSpacesNonBreaking) {
    if (!mHtmlEncodeElement) {
      mHtmlEncodeElement = $('<div/>');
    }

    value += "";
    value = value.replace(/\n/g, "~br~");
    value = mHtmlEncodeElement.text(value).html();
    if (makeSpacesNonBreaking) {
      value = value.replace(/ /g, "&nbsp;");
    }
    value = value.replace(/~br~/g, "<br/>");
    return value;
  }

  // ================================================================
  // PUBLIC: Initialise Address Auto-Complete for a group of controls
  // ================================================================
  function InitialiseAddressAutoComplete(options) {
    // Extend options with defaults
    options = $.extend({},
      {
        service: "default",
        propertyName: null,
        streetAddress: null,
        suburb: null,
        city: null,
        state: null,
        postcode: null,
        country: null,

        onAfterAddressAutoComplete: null,
      }, options);

    // Get default service
    if (options.service == "default") {
      options.service = "google-maps-3";
    }

    // Configure address controls
    if (options.streetAddress && options.streetAddress.Text) {
      // Dealing with proper Widget controls
    }
    else {
      // Dealing with HTML Input elements
      if (options.propertyName) $("#" + options.propertyName).attr("maxlength", 50);
      if (options.streetAddress) $("#" + options.streetAddress).attr("maxlength", 130);
      if (options.suburb) $("#" + options.suburb).attr("maxlength", 50);
      if (options.city) $("#" + options.city).attr("maxlength", 50);
      if (options.postcode) $("#" + options.postcode).attr("maxlength", 10);
    }

    // Initialise Auto-Complete
    switch (options.service) {
      case "google-maps-3":
        InitialiseAddressAutoComplete_GoogleMaps3(options);
        break;

      default:
        widget.RegisterError("widget_ui.InitialiseAddressAutoComplete: service '" + options.service + "' is not a valid service.");
    }
  }

  function InitialiseAddressAutoComplete_GoogleMaps3(options) {
    // Validate
    var apiKey = widget.Options.googleMapsApiKey;
    if (!apiKey) {
      console.warn("widget_ui.InitialiseAddressAutoComplete: No Browser API Key is defined for the Google Maps API. This must be defined under Global Settings, Clients, Addressing within finPOWER Connect.");
      return;
    }

    // Initialise
    if (mAddressingGoogleMaps3Initialised) {
      if (mAddressingGoogleMaps3Initialising) {
        // Still initialising
        mAddressingGoogleMaps3CallbackList.push(options);
      }
      else {
        // Initialised
        InitialiseAddressAutoComplete_GoogleMaps3_Done(options);
      }
    }
    else {
      mAddressingGoogleMaps3Initialised = true;
      mAddressingGoogleMaps3Initialising = true;
      var s = document.createElement("script");
      s.setAttribute("type", "text/javascript");
      s.setAttribute("src", "https://maps.googleapis.com/maps/api/js?v=3.exp&key=" + apiKey + "&libraries=places&callback=gMapsLoadedCallback&region=" + widget.Options.countryCode);
      (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(s);
      window.gMapsLoadedCallback = function () { InitialiseAddressAutoComplete_GoogleMaps3_Done(options); };
    }
  }

  function InitialiseAddressAutoComplete_GoogleMaps3_Done(options) {
    // Perform callback list
    if (mAddressingGoogleMaps3Initialising) {
      mAddressingGoogleMaps3Initialising = false;
      for (var i = 0; i < mAddressingGoogleMaps3CallbackList.length; i++) {
        InitialiseAddressAutoComplete_GoogleMaps3_Done(mAddressingGoogleMaps3CallbackList[i]);
      }
    }

    // Create auto-complete
    var autocomplete1;
    var searchBox;
    if (options.streetAddress && options.streetAddress.Text) {
      // Dealing with proper Widget controls
      searchBox = options.streetAddress.Element()[0];
      autocomplete1 = new google.maps.places.Autocomplete(searchBox, { types: ["geocode"] });
    }
    else {
      // Dealing with HTML Input element
      searchBox = document.getElementById(options.streetAddress);
      autocomplete1 = new google.maps.places.Autocomplete(searchBox, { types: ["geocode"] });
    }

    google.maps.event.addListener(autocomplete1, "place_changed", function () {
      var place = autocomplete1.getPlace();

      // Revert back to old value if read-only HTML Widget control
      if (options.streetAddress && options.streetAddress.Text) {
        if (options.streetAddress.ReadOnly()) {
          options.streetAddress.Text(options.streetAddress.TextOriginal());
        }
      }

      // If street address is the only input then nothing else to do
      if (!options.suburb && !options.city && !options.country) {
        // Focus
        if (options.streetAddress && options.streetAddress.Text) options.streetAddress.Focus();

        // Notify
        if (options.onAfterAddressAutoComplete) options.onAfterAddressAutoComplete();
        return;
      }

      // Locate Country
      var country = "";
      for (var i = 0; i < place.address_components.length; i++) {
        var addressType = place.address_components[i].types[0];
        var val = place.address_components[i].long_name;

        if (addressType == "country") {
          switch (val.toUpperCase()) {
            case "AUSTRALIA":
              country = "Australia";
              break;

            case "NEW ZEALAND":
              country = "New Zealand";
              break;

            case "UNITED KINGDOM":
              country = "United Kingdom";
              break;

            default:
              country = val;
              break;
          }
        }
      }

      // Get address details
      var ad;
      switch (country) {
        case "Australia":
          ad = InitialiseAddressAutoComplete_GoogleMaps3_Done_AU(options, place);
          break;

        case "New Zealand":
          ad = InitialiseAddressAutoComplete_GoogleMaps3_Done_NZ(options, place, $(searchBox).val());
          break;

        case "United Kingdom":
          ad = InitialiseAddressAutoComplete_GoogleMaps3_Done_UK(options, place);
          break;

        default:
          ad = InitialiseAddressAutoComplete_GoogleMaps3_Done_Generic(options, place);
          break;
      }

      // Normalise address values (i.e., set to blank string if undefined)
      if (!ad.propertyName) ad.propertyName = "";
      if (!ad.streetAddress) ad.streetAddress = "";
      if (!ad.suburb) ad.suburb = "";
      if (!ad.city) ad.city = "";
      if (!ad.state) ad.state = "";
      if (!ad.postcode) ad.postcode = "";
      if (!ad.country) ad.country = "";

      // Handle Street Unit, e.g., "2/12 Flinders Parade"
      // NOTE: Google will not have returned the "/12" part but we can push that back in below
      if (options.streetAddress && options.streetAddress.Text && ad.streetAddress.toUpperCase() != options.streetAddress.Text().toUpperCase()) {
        // Widget controls
        var s = options.streetAddress.Text();
        var n = s.indexOf(" ");
        if (n != -1) {
          var number = s.substr(0, n);
          var nNew = ad.streetAddress.indexOf(" ");
          if (nNew != -1) {
            var numberNew = ad.streetAddress.substr(0, nNew);
            if (number.endsWith("/" + numberNew) || number.startsWith(numberNew + "/")) {
              // Update street address to include Unit
              ad.streetAddress = number + ad.streetAddress.substr(nNew);
            }
          }
        }
      }
      else if (typeof options.streetAddress == "string") {
        // Standard HTML controls, defined by id
        var sae = $("#" + options.streetAddress);
        var s = sae.val();
        var n = s.indexOf(" ");
        if (n != -1) {
          var number = s.substr(0, n);
          var nNew = ad.streetAddress.indexOf(" ");
          if (nNew != -1) {
            var numberNew = ad.streetAddress.substr(0, nNew);
            if (number.endsWith("/" + numberNew) || number.startsWith(numberNew + "/")) {
              // Update street address to include Unit
              ad.streetAddress = number + ad.streetAddress.substr(nNew);
            }
          }
        }
      }

      // Populate fields
      if (options.streetAddress && options.streetAddress.Text) {
        // Dealing with proper Widget controls
        if (options.streetAddress && options.streetAddress.ReadOnly()) {
          // Read-only
        }
        else {
          if (options.propertyName) options.propertyName.Text(ad.propertyName);
          if (options.streetAddress) options.streetAddress.Text(ad.streetAddress);
          if (options.suburb) options.suburb.Text(ad.suburb);
          if (options.city) options.city.Text(ad.city);
          if (options.state) options.state.Text(ad.state);
          if (options.postcode) options.postcode.Text(ad.postcode);
          if (options.country) options.country.Text(ad.country);
        }
      }
      else {
        // Dealing with HTML Input element
        $("#" + options.propertyName).val(ad.propertyName);
        $("#" + options.streetAddress).val(ad.streetAddress);
        $("#" + options.suburb).val(ad.suburb);
        $("#" + options.city).val(ad.city);
        $("#" + options.state).val(ad.state);
        $("#" + options.postcode).val(ad.postcode);
        $("#" + options.country).val(ad.country);

        // Update street address (blur and focus on suburb, otherwise when leaving street address, it gets updated with the full address again!)
        // WARNING: Known issue in IE (10?). If you use Enter to select the address, it leaves the full address in the street address field
        $("#" + options.streetAddress).trigger("blur");
        $("#" + options.streetAddress).val(ad.streetAddress);
        if (options.suburb) {
          $("#" + options.suburb).focus();
        }
        else {
          $("#" + options.city).focus();
        }
      }

      // Notify
      if (options.onAfterAddressAutoComplete) options.onAfterAddressAutoComplete();
    });
  }

  /* Generic (i.e., unhandled country) */
  function InitialiseAddressAutoComplete_GoogleMaps3_Done_Generic(options, place) {
    var ad = {};

    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      var val = place.address_components[i].long_name;

      switch (addressType) {
        case "premise":
          ad.propertyName = val;
          break;

        case "street_number":
          ad.streetAddress = val;
          break;

        case "route":
          if (!ad.streetAddress) ad.streetAddress = "";
          ad.streetAddress += " " + val;
          break;

        case "locality":
          if (!ad.suburb) ad.suburb = val;
          break;

        case "neighborhood":
          ad.suburb = val;
          break;

        case "locality":
          ad.city = val;
          break;

        case "administrative_area_level_1":
          ad.state = val;
          break;

        case "postal_code":
          ad.postcode = val;
          break;

        case "country":
          ad.country = val;
          break;

        default:
          //window.alert(addressType + ": " + val);
          break;
      }
    }

    return ad;
  }

  /* Australia */
  function InitialiseAddressAutoComplete_GoogleMaps3_Done_AU(options, place) {
    var ad = {};

    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      var val = place.address_components[i].long_name;

      switch (addressType) {
        case "premise":
          ad.propertyName = val;
          break;

        case "street_number":
          ad.streetAddress = val;
          break;

        case "route":
          if (!ad.streetAddress) ad.streetAddress = "";
          ad.streetAddress += " " + val;
          break;

        //case "sublocality_level_1":
        //  ad.suburb = val;
        //  break;

        case "locality":
          // NOTE: City is used as Suburb in AU
          ad.suburb = val;
          break;

        case "administrative_area_level_2":
          ad.city = val;
          break;

        case "administrative_area_level_1":
          ad.state = val;
          break;

        case "postal_code":
          ad.postcode = val;
          break;

        case "country":
          ad.country = val;
          break;

        default:
          //window.alert(addressType + ": " + val);
          break;
      }
    }

    return ad;
  }

  /* New Zealand */
  function InitialiseAddressAutoComplete_GoogleMaps3_Done_NZ(options, place, searchString) {
    var ad = {};

    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      var val = place.address_components[i].long_name;

      switch (addressType) {
        case "premise":
          ad.propertyName = val;
          break;

        case "street_number":
          ad.streetAddress = val;
          break;

        case "route":
          if (!ad.streetAddress) ad.streetAddress = "";
          ad.streetAddress += " " + val;
          break;

        case "sublocality_level_1":
          ad.suburb = val;
          break;

        case "locality":
          ad.city = val;
          break;

        case "administrative_area_level_1":
          ad.state = val;
          break;

        case "postal_code":
          ad.postcode = val;
          break;

        case "country":
          ad.country = val;
          break;

        default:
          //window.alert(addressType + ": " + val);
          break;
      }
    }

    // FIX: Addresses such as "812 Bledisloe Napier" remove the street number and Google does not appear to return it!
    if (ad.streetAddress && !/\d/.test(ad.streetAddress)) {
      var n = parseInt(searchString);
      if (n) ad.streetAddress = n + ad.streetAddress;
    }

    return ad;
  }

  /* United Kingdom */
  function InitialiseAddressAutoComplete_GoogleMaps3_Done_UK(options, place) {
    var ad = {};

    for (var i = 0; i < place.address_components.length; i++) {
      var addressType = place.address_components[i].types[0];
      var val = place.address_components[i].long_name;

      switch (addressType) {
        case "premise":
          ad.propertyName = val;
          break;

        case "street_number":
          ad.streetAddress = val;
          break;

        case "route":
          if (!ad.streetAddress) ad.streetAddress = "";
          ad.streetAddress += " " + val;
          break;

        case "administrative_area_level_2":
          ad.state = val;
          break;

        case "locality":
          if (!ad.suburb) ad.suburb = val;
          break;

        case "neighborhood":
          ad.suburb = val;
          break;

        case "postal_town":
          ad.city = val;
          break;

        case "postal_code_prefix":
          if (!ad.postcode) ad.postcode = val;
          break;

        case "postal_code":
          ad.postcode = val;
          break;

        case "country":
          // NOTE: Don't want UK as country, we want England etc
          //ad.country = val;
          break;

        case "administrative_area_level_1":
          // NOTE: Don't want UK as country, we want England etc
          ad.country = val;
          break;

        default:
          //window.alert(addressType + ": " + val);
          break;
      }
    }

    // Tidy up
    if (ad.suburb == ad.city) ad.suburb = "";  // E.g., prevent Horsham, Horsham

    return ad;
  }

  // ========================================================
  // PUBLIC: Indicates whether this is a Small Mobile Browser
  // ========================================================
  function IsSmallMobileBrowser() {
    return mIsSmallMobileBrowser;
  }

  // ================================================
  // PUBLIC: Order Elements within a parent container
  // ================================================
  function OrderElements(containerElement, tagName, orderAttributeName, desc) {
    // Sort
    containerElement.find(tagName).sort(function (a, b) {
      var i1 = $(a).attr(orderAttributeName);
      var i2 = $(b).attr(orderAttributeName);

      if (desc) {
        return i2 - i1;
      }
      else {
        return i1 - i2;
      }
    }).appendTo(containerElement);
  }

  // =======================================================================================================================
  // PUBLIC: Scroll Document Body so element is at the top or if no element supplied, scroll to the top of the document body
  // =======================================================================================================================
  function ScrollToTop(e) {
    if (e) {
      // Scroll element to the top, i.e., into view
      e = GetElement(e);

      var top = e.offset().top + $("body").scrollTop();
      var t = window.setTimeout(function () {
        window.clearTimeout(t);
        t = null;

        $("body").animate({ scrollTop: top });
      }, 10);
    }
    else {
      // Scroll document body to the top
      var t = window.setTimeout(function () {
        window.clearTimeout(t);
        t = null;

        $("html,body").animate({ scrollTop: 0 });
      }, 10);
    }
  }

  // ======================================
  // PUBLIC: Select a Document Manager File
  // ======================================
  function SelectDocumentManagerFile(sourceType, sourceId, options, callback) {
    // Create Modal
    var Modal = widget.UI.Modal({
      title: "Select Document Manager File",
      height: "90%",
      maxWidth: "600px",
      maxHeight: "1200px",
      minWidth: "320px",
      minHeight: "320px",
      closeOnEscape: true,
    });

    // Extend options
    options = $.extend({},
      {
        fileTypes: "",
      },
      options);

    // Define HTML Content
    var content = "";
    content += "<div class='is-dock-fill is-select-document-manager-file'></div>";

    // Show (content will be set in the next block)
    Modal.Show({ content: content });

    // Block UI
    Modal.WaitShow("Retrieving file list, please wait...");

    // Fetch List
    var params = { sourceType: sourceType, sourceId: sourceId, fileTypes: options.fileTypes };

    // Cached?
    var cacheKey = JSON.stringify(params);
    if (window.__SelectDocumentManagerFile_CacheKey && window.__SelectDocumentManagerFile_CacheKey == cacheKey) {
      SelectDocumentManagerFile_BuildList(Modal, callback, window.__SelectDocumentManagerFile_Cache);
    }
    else {
      // Fetch
      widget._SystemGetString("DocumentManagerComboBox_GetList", params,
        function (data) {
          // Cache
          window.__SelectDocumentManagerFile_CacheKey = cacheKey;
          window.__SelectDocumentManagerFile_Cache = data;

          // Build List
          SelectDocumentManagerFile_BuildList(Modal, callback, data);
        },

        function (data) {
          // Unblock UI
          Modal.WaitHide();

          widget.RegisterError("widget_ui.SelectDocumentManagerFile: Failed to refresh details: " + data);
        });
    }
  }

  function SelectDocumentManagerFile_BuildList(modal, callback, data) {
    // Parse
    data = JSON.parse(data);

    // Render
    var e = $("div", modal.ContentElement());

    // Define Content
    for (var i = 0; i < data.length; i++) {
      var s = data[i];
      var icon = "Document";
      var n = s.lastIndexOf(".");
      if (n > 0) {
        var extension = s.substr(n + 1).toUpperCase();
        switch (extension) {
          case "BMP":
          case "GIF":
          case "ICO":
          case "JPG":
          case "JPEG":
          case "PNG":
            icon = "Image";
            break;

          case "DOC":
          case "DOCX":
            icon = "DocumentType_Word";
            break;

          case "PDF":
            icon = "DocumentType_PDF";
            break;

          case "XLS":
          case "XLSX":
            icon = "DocumentType_Excel";
            break;

        }
      }

      var elFile = $("<div><img src='" + widget.GetIconUrl(icon, 32) + "'/><div>" + HtmlEncode(s) + "</div></div>");
      e.append(elFile);

      (function (fileName) { elFile.click(function () { modal.Hide(true); callback(fileName); }); })(s);
    }


    // Unblock UI
    modal.WaitHide();

    // Focus
    e.focus();

    // Warning
    if (data.length == 0) {
      widget.UI.MsgBoxAlert("There are no available Document Manager files to select.", {}, function () { modal.Hide(true); });
    }
  }

  // ============================
  // PUBLIC: Select a Flag Colour
  // ============================
  function SelectFlagColour(list, options, callback) {
    // Default list is as per finWorkflowFunctions.CommonColourFlagsList
    if (!list) list = "Black,Blue,Green,Cyan,Red,Magenta,Yellow,White,Gray,LightBlue,LightGreen,LightCyan,Pink,Plum,LightYellow,Orange";

    // Convert list to array
    if (typeof list == "string") {
      list = ArrayFromCsvString(list);
    }

    // Create Modal
    var Modal = widget.UI.Modal({
      title: "Select Flag Colour",
      height: "80%",
      maxWidth: "420px",
      maxHeight: "420px",
      minWidth: "320px",
      minHeight: "320px",
      closeOnEscape: true,
    });

    // Define HTML Content
    var content = "";
    content += "<div class='is-dock-fill is-select-flag-colour'></div>";

    // Show (content will be set in the next block)
    Modal.Show({ content: content });

    // Render
    var e = $("div", Modal.ContentElement());

    // Define Content
    var elClear = $("<div title='Clear Flag'><img src='" + widget.GetIconUrl("Flag[Gray]", 32, "Clear") + "'/></div>");
    e.append(elClear);
    elClear.click(function () { Modal.Hide(true); callback(""); });

    for (var i = 0; i < list.length; i++) {
      var s = list[i];
      var elFlag = $("<div title='" + s + "'><img src='" + widget.GetIconUrl("Flag[" + s + "]", 32) + "'/></div>");
      e.append(elFlag);

      (function (colour) { elFlag.click(function () { Modal.Hide(true); callback(colour); }); })(s);
    }

    // Focus
    e.focus();
  }

  // =========================
  // PUBLIC: Select a Resource
  // =========================
  function SelectResource(options, callback) {
    // Create Modal
    var Modal = widget.UI.Modal({
      title: "Select Resource",
      height: "90%",
      maxWidth: "600px",
      maxHeight: "1200px",
      minWidth: "320px",
      minHeight: "320px",
      closeOnEscape: true,
    });

    // Extend options
    options = $.extend({},
      {
        includeAll: false,
        includeAllowAsEmailAttachment: true,
        fileTypes: "",
      },
      options);

    // Define HTML Content
    var content = "";
    content += "<div class='is-dock-fill is-select-document-manager-file'></div>";

    // Show (content will be set in the next block)
    Modal.Show({ content: content });

    // Block UI
    Modal.WaitShow("Retrieving resource list, please wait...");

    // Fetch List
    var params = { resourceTypes: options.fileTypes, includeAll: options.includeAll, includeAllowAsEmailAttachment: options.includeAllowAsEmailAttachment };

    // Cached?
    var cacheKey = JSON.stringify(params);
    if (window.__SelectResource_CacheKey && window.__SelectResource_CacheKey == cacheKey) {
      SelectResource_BuildList(Modal, callback, window.__SelectResource_Cache);
    }
    else {
      // Fetch
      widget._SystemGetString("SelectResource_GetList", params,
        function (data) {
          // Cache
          window.__SelectResource_CacheKey = cacheKey;
          window.__SelectResource_Cache = data;

          // Build List
          SelectResource_BuildList(Modal, callback, data);
        },

        function (data) {
          // Unblock UI
          Modal.WaitHide();

          widget.RegisterError("widget_ui.SelectResource: Failed to refresh details: " + data);
        });
    }
  }

  function SelectResource_BuildList(modal, callback, data) {
    // Parse
    data = JSON.parse(data);

    // Render
    var e = $("div", modal.ContentElement());
        
    // Define Content
    for (var i = 0; i < data.length; i++) {
      var item = data[i];

      var icon = "Document";
      switch (item.ResourceType) {
        case "DocumentDoc":
        case "DocumentDocx":
          icon = "DocumentType_Word";
          break;

        case "DocumentPdf":
          icon = "DocumentType_PDF";
          break;

        case "ImageJpeg":
        case "ImagePng":
        case "ImageSvg":
          icon = "Image";
          break;
      }

      var elFile = $("<div><img src='" + widget.GetIconUrl(icon, 32) + "'/><div>" + HtmlEncode(item.Description) + "</div></div>");
      e.append(elFile);

      (function (item) { elFile.click(function () { modal.Hide(true); callback(item.ResourceId, item.Description, item.ResourceType, item.SizeBytes); }); })(item);
    }

    // Unblock UI
    modal.WaitHide();

    // Focus
    e.focus();

    // Warning
    if (data.length == 0) {
      widget.UI.MsgBoxAlert("There are no available Resources to select.", {}, function () { modal.Hide(true); });
    }
  }

  // =====================
  // PUBLIC: Select a Date
  // =====================
  function GetInputDate(message, options, okCallback, cancelCallback) {
    // Just in case!
    message = "" + message;

    // Defaults
    options.allowBlank = undefined ? true : options.allowBlank;

    // Create Modal
    var Modal = widget.UI.Modal({
      title: options.title || "Specify a Date",
      height: "80%",
      maxWidth: "420px",
      maxHeight: "420px",
      minWidth: "320px",
      minHeight: "320px",
      closeOnEscape: true,
    });
    var actions = [
      { groupId: "[buttons]", actionId: "Ok", caption: "OK" },
      { groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
    ];
    Modal.Actions().Define(actions);

    // Define HTML Content
    var content = "";
    content += "<div class='is-dock-fill is-get-input'></div>";

    // Show (content will be set in the next block)
    Modal.Show({ content: content });

    // Render
    var e = $("div", Modal.ContentElement());

    // Define Content
    if (message) {
      var eMessage = $("<div></div>");
      if (options.messageIsHtml) {
        eMessage.html(message);
      }
      else {
        eMessage.text(message);
      }
      e.append(eMessage);
    }

    e.append("<div class='is-get-input-input'><input/></div>");
    var datebox = DateBox($(".is-get-input-input > input", e), {
      allowBlank: options.allowBlank,
    });
    if (options.value) datebox.Value(options.value);
    if (options.maxValue) datebox.MaxValue(options.maxValue);
    if (options.minValue) datebox.MinValue(options.minValue);

    // Handle Actions
    Modal.OnAction(function (actionId) {
      switch (actionId) {
        case "Cancel":
          Modal.Hide(true);
          if (cancelCallback) cancelCallback();
          break;

        default:
          var valid = true;

          if (!options.allowBlank && !datebox.Value()) {
            valid = false;
          }
          else {
            datebox.Validate();
            valid = datebox.IsValid();
          }

          if (valid) {
            Modal.Hide(true);
            if (okCallback) okCallback(datebox.Value());
          }
          else {
            datebox.Focus();
          }
          break;
      }
    });

    // Focus
    var t = window.setTimeout(function () {
      window.clearTimeout(t);
      t = null;

      datebox.Focus();
    }, 10);
  }

  // ==========================
  // PUBLIC: Select a Date Time
  // ==========================
  function GetInputDateTime(message, options, okCallback, cancelCallback) {
    // Just in case!
    message = "" + message;

    // Defaults
    options.allowBlank = undefined ? true : options.allowBlank;

    // Create Modal
    var Modal = widget.UI.Modal({
      title: options.title || "Specify a Date and Time",
      height: "80%",
      maxWidth: "500px",
      maxHeight: "420px",
      minWidth: "320px",
      minHeight: "320px",
      closeOnEscape: true,
    });
    var actions = [
      { groupId: "[buttons]", actionId: "Ok", caption: "OK" },
      { groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
    ];
    Modal.Actions().Define(actions);

    // Define HTML Content
    var content = "";
    content += "<div class='is-dock-fill is-get-input'></div>";

    // Show (content will be set in the next block)
    Modal.Show({ content: content });

    // Render
    var e = $("div", Modal.ContentElement());

    // Define Content
    if (message) {
      var eMessage = $("<div></div>");
      if (options.messageIsHtml) {
        eMessage.html(message);
      }
      else {
        eMessage.text(message);
      }
      e.append(eMessage);
    }

    e.append("<div class='is-get-input-input'><div></div></div>");
    var datebox = DateTimeZone($(".is-get-input-input > div", e), {
      allowBlank: options.allowBlank,
    });
    if (options.value) datebox.Value(options.value);
    if (options.maxValue) datebox.MaxValue(options.maxValue);
    if (options.minValue) datebox.MinValue(options.minValue);

    // Handle Actions
    Modal.OnAction(function (actionId) {
      switch (actionId) {
        case "Cancel":
          Modal.Hide(true);
          if (cancelCallback) cancelCallback();
          break;

        default:
          var valid = true;

          if (!options.allowBlank && !datebox.Value()) {
            valid = false;
          }
          else {
            //datebox.Validate();
            valid = datebox.IsValid();
          }

          if (valid) {
            Modal.Hide(true);
            if (okCallback) okCallback(datebox.Value(), datebox.TimeZoneId());
          }
          else {
            datebox.Focus();
          }
          break;
      }
    });

    // Focus
    var t = window.setTimeout(function () {
      window.clearTimeout(t);
      t = null;

      datebox.Focus();
    }, 10);
  }

  // ====================================================================
  // PUBLIC: Convert a named colour such as "Red" to RGB, e.g., "#FF0000"
  // ====================================================================
  function HtmlNamedColourToRgb(namedColour) {
    if (!namedColour) return "#000000";
    if ((namedColour + "").startsWith("#")) return namedColour;

    var colours = {
      "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aqua": "#00ffff", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "black": "#000000", "blanchedalmond": "#ffebcd", "blue": "#0000ff", "blueviolet": "#8a2be2", "brown": "#a52a2a", "burlywood": "#deb887", "cadetblue": "#5f9ea0", "chartreuse": "#7fff00", "chocolate": "#d2691e", "coral": "#ff7f50", "cornflowerblue": "#6495ed", "cornsilk": "#fff8dc", "crimson": "#dc143c", "cyan": "#00ffff", "darkblue": "#00008b", "darkcyan": "#008b8b", "darkgoldenrod": "#b8860b", "darkgray": "#a9a9a9", "darkgreen": "#006400", "darkkhaki": "#bdb76b", "darkmagenta": "#8b008b", "darkolivegreen": "#556b2f", "darkorange": "#ff8c00", "darkorchid": "#9932cc", "darkred": "#8b0000", "darksalmon": "#e9967a", "darkseagreen": "#8fbc8f", "darkslateblue": "#483d8b", "darkslategray": "#2f4f4f", "darkturquoise": "#00ced1", "darkviolet": "#9400d3", "deeppink": "#ff1493", "deepskyblue": "#00bfff", "dimgray": "#696969", "dodgerblue": "#1e90ff", "firebrick": "#b22222", "floralwhite": "#fffaf0", "forestgreen": "#228b22", "fuchsia": "#ff00ff", "gainsboro": "#dcdcdc", "ghostwhite": "#f8f8ff", "gold": "#ffd700", "goldenrod": "#daa520", "gray": "#808080", "green": "#008000", "greenyellow": "#adff2f",
      "honeydew": "#f0fff0", "hotpink": "#ff69b4", "indianred ": "#cd5c5c", "indigo": "#4b0082", "ivory": "#fffff0", "khaki": "#f0e68c", "lavender": "#e6e6fa", "lavenderblush": "#fff0f5", "lawngreen": "#7cfc00", "lemonchiffon": "#fffacd", "lightblue": "#add8e6", "lightcoral": "#f08080", "lightcyan": "#e0ffff", "lightgoldenrodyellow": "#fafad2", "lightgrey": "#d3d3d3", "lightgreen": "#90ee90", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a", "lightseagreen": "#20b2aa", "lightskyblue": "#87cefa", "lightslategray": "#778899", "lightsteelblue": "#b0c4de", "lightyellow": "#ffffe0", "lime": "#00ff00", "limegreen": "#32cd32", "linen": "#faf0e6", "magenta": "#ff00ff", "maroon": "#800000", "mediumaquamarine": "#66cdaa", "mediumblue": "#0000cd", "mediumorchid": "#ba55d3", "mediumpurple": "#9370d8", "mediumseagreen": "#3cb371", "mediumslateblue": "#7b68ee", "mediumspringgreen": "#00fa9a", "mediumturquoise": "#48d1cc", "mediumvioletred": "#c71585", "midnightblue": "#191970", "mintcream": "#f5fffa", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5", "navajowhite": "#ffdead", "navy": "#000080", "oldlace": "#fdf5e6", "olive": "#808000", "olivedrab": "#6b8e23", "orange": "#ffa500", "orangered": "#ff4500", "orchid": "#da70d6", "palegoldenrod": "#eee8aa",
      "palegreen": "#98fb98", "paleturquoise": "#afeeee", "palevioletred": "#d87093", "papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "peru": "#cd853f", "pink": "#ffc0cb", "plum": "#dda0dd", "powderblue": "#b0e0e6", "purple": "#800080", "rebeccapurple": "#663399", "red": "#ff0000", "rosybrown": "#bc8f8f", "royalblue": "#4169e1", "saddlebrown": "#8b4513", "salmon": "#fa8072", "sandybrown": "#f4a460", "seagreen": "#2e8b57", "seashell": "#fff5ee", "sienna": "#a0522d", "silver": "#c0c0c0", "skyblue": "#87ceeb", "slateblue": "#6a5acd", "slategray": "#708090", "snow": "#fffafa", "springgreen": "#00ff7f", "steelblue": "#4682b4", "tan": "#d2b48c", "teal": "#008080", "thistle": "#d8bfd8", "tomato": "#ff6347", "turquoise": "#40e0d0", "violet": "#ee82ee", "wheat": "#f5deb3", "white": "#ffffff", "whitesmoke": "#f5f5f5", "yellow": "#ffff00", "yellowgreen": "#9acd32"
    };

    if (colours[namedColour.toLowerCase()] === undefined) {
      return "#000000";
    }
    else {
      return colours[namedColour.toLowerCase()];
    }
  }

  // ===========================
  // PUBLIC: Show a Notification
  // ===========================
  function ShowNotification(type, message, details, title, icon) {
    if (type == undefined) type = "";
    if (message == undefined) message = "";
    if (details == undefined) details = "";
    if (title == undefined) title = "";
    if (icon == undefined) icon = "";

    widget.ExecuteApplicationShortcutUrl("app://uinotification?type=" + encodeURIComponent(type) + "&message=" + encodeURIComponent(message) + "&details=" + encodeURIComponent(details) + "&title=" + encodeURIComponent(title) + "&icon=" + encodeURIComponent(icon));
  }

  // ==============================================
  // PUBLIC: Add Rows to a table (or tbody) element
  // ==============================================
  function TableAddRowsFromCollection(e, array, fieldList, formatCallback) {
    e = GetElement(e);

    // Validate
    if (!e || !array || array.length == 0) return;

    // Find header row (so we can inherit cell alignment)
    var theadRow;
    if (e.prop("tagName") == "TBODY") {
      var parent = e.parent();
      if (parent && parent.prop("tagName") == "TABLE") {
        theadRow = $("thead > tr > th", parent);
      }
    }
    else if (e.prop("tagName") == "TABLE") {
      theadRow = $("thead > tr > th", e);
    }

    // Get Field List
    var fields;
    if (fieldList) {
      fields = fieldList.split(",");
    }
    else {
      fields = [];
      for (var k in array[0]) {
        fields.push(array[k]);
      }
    }

    // Add Rows
    for (var i = 0; i < array.length; i++) {
      // Get item
      var record = array[i];

      // Create row
      var tr = $("<tr></tr>");

      // Add cells
      for (var j = 0; j < fields.length; j++) {
        // Create cell
        var td = $("<td></td>");
        td.text(record[fields[j]]);

        // Inherit Text Alignment from Header
        if (theadRow && j < theadRow.length) {
          var s = $(theadRow[j]).css("text-align");
          if (s) td.css("text-align", s);
        }

        // Append to row
        tr.append(td);

        // Callback to format
        if (formatCallback) {
          var o = { rowIndex: i, record: record, field: record[fields[j]], fieldName: fields[j], row: tr, cellIndex: j, cell: td, html: null };
          try {
            formatCallback(o);

            // Update cell value
            if (o.html != null) {
              td.html(o.html);
            }
          }
          catch (e) {
          }
        }
      }

      // Append row
      e.append(tr);
    }
  }

  // =================================================================================
  // PUBLIC: Validate controls have been entered and are valid for a container Element
  // =================================================================================
  function ValidateContainer(container, tabs, tabIndex, allControls) {
    var el, e, e2, ej;
    var Ok, Include;

    // Assume Success
    Ok = true;

    // Iterate controls
    var found = false;
    el = $("input,select,textarea,div.is-grid-container,span[controltype='radiobuttonlist'],span[controltype='checklist'],span[controltype='fileupload'],div.is-parametershost-container", container);
    for (var i = 0; i < el.length; i++) {
      var Ok2 = true;

      e = el[i];
      ej = $(e);

      // Include?
      if (ej.css("display") == "none") {
        // Hidden (directly)
        Include = false;
      }
      else if (ej.attr("readonly") == "readonly") {
        // Read-Only
        Include = false;
      }
      else {
        // A common way of hiding controls is to hide their parent, e.g., a tr, tbody or table element etc so travel back up the tree until we hit something that won't be hidden
        Include = true;
        e2 = ej;

        while (e2) {
          e2 = e2.parent();
          var tagName = e2.prop("tagName");
          if (tagName == "BODY") {
            break;
          }
          else if (tagName == "DIV") {
            if (e2.hasClass("is-tab-page")) {
              // Tab page so will always be hidden if not for the selected tab
              // TODO: What about pages that are not included, e.g., the Document page on a Log form?
              break;
            }
            else if (e2.hasClass("is-parametershost-container")) {
              // Parameters Host may be hidden
              var ctlPh = e2.prop("is-control");
              if (ctlPh && ctlPh.TypeName == "ParametersHost") {
                Include = ctlPh.Visible();
              }
              break;
            }
          }
          else {
            if (e2.css("display") == "none" || e2.css("visibility") == "hidden") {
              Include = false;
              break;
            }
          }
        }
      }

      // Get control
      var ctl = ej ? ej.prop("is-control") : null;

      // Check we have an id attribute (just in case, and only if a real control is not involved)
      // NOTE: templateid is used by the repeater control
      if (Include && !ctl && !ej.attr("id") && !ej.attr("templateid")) Include = false;

      // Special
      if (Include && ctl) {
        switch (ctl.TypeName) {
          case "FileUpload":
            // File Upload
            Ok = ctl.IsValid();

            // Don't do standard validation stuff
            if (!Ok) {
              widget.UI.MsgBoxAlert(ctl.ValidationMessage(), { messageIsHtml: true }, function () { ctl.Focus(); });
              return false;
            }
            break;

          case "ParametersHost":
            // Parameters Host
            // NOTE: This is additional validation, on top of each controls normal validation such as allowBlank
            if (ctl.Visible()) {
              Ok = ctl.Validate();
            }

            // Select correct Tab page
            if (!Ok && tabs) {
              tabs.SelectedTabIndex(tabIndex);
            }

            // Don't do standard validation stuff
            // NOTE: Parameters Host only validates special conditions such as mismatched number and date ranges
            if (!Ok) return false;
            break;
        }
      }

      // Check
      if (Include) {
        // Check max and min values etc
        if (Ok2 && ctl && ctl.Validate) {
          Ok2 = ctl.Validate();
        }

        // Check mandatory
        // NOTE: If we have a control, the mandatory state will have been checked in the above block
        if (Ok2 && !ctl && ej.hasClass("is-mandatory")) {
          if (!widget.RTrim(ej.val())) {
            Ok2 = false;
          }
        }
      }

      // Focus and exit?
      if (!Ok2) {
        Ok = false;
        var ctlid = ej.attr("id");
        if (!ctlid && ctl && ctl.Caption) ctlid = ctl.Caption();
        console.log("widget.UI.ValidateContainer: Stopped at control '" + ctlid + "'.");

        // Select correct Tab page
        if (tabs) {
          tabs.SelectedTabIndex(tabIndex);
        }

        // Focus (only on the first control though if checking all controls)
        if (!found) {
          found = true;

          if (ctl && ctl.Focus) {
            ctl.Focus();
          }
          else {
            ej.focus();
          }
        }

        // Exit now?
        if (!allControls) break;
      }
    }

    return Ok;
  }



  // ====================================
  // PUBLIC: Evaluate special Widget tags
  // ====================================
  function Evaluate(e, options) {
    // Extend options with defaults
    options = $.extend({},
      {
        context: null,
      }, options);

    // Get Element
    if (!e) e = $(document);
    if (typeof e == "string") {
      e = $("#" + e);
    }
    else {
      id = $(e).attr("id");
    }

    // Firstly, replace all templates
    var s = "";
    var els = $("*[ng-template]", e);
    for (var i = 0; i < els.length; i++) {
      var el = $(els[i]);

      // -----------
      // ng-template
      // -----------
      s = el.attr("ng-template");
      if (s) {
        var te = $("#" + s);
        if (te.length == 0) {
          console.warn("widget.UI.Evaluate: ng-template '" + s + "' not found. No element with this id exists.");
        }
        else {
          var html = te.html();
          if (html) {
            el.html(html);
          }
          else {
            console.warn("widget.UI.Evaluate: ng-template '" + s + "' does not contain any child elements.");
          }
        }
      }
    }

    // Get elements containing tags within the element and including the element
    els = $("*[ng-show],*[ng-hide],*[ng-bind],*[ng-bind-html],*[ng-if],*[ng-class],*[ng-repeat],*[ng-bind-attribute-name]", e);

    // Create a global eval object (avoids minimized variable names that may collide with local variables in the class)
    var geval = eval;

    // Evaluate
    for (var i = 0; i < els.length; i++) {
      var el = $(els[i]);

      // -------
      // ng-show
      // -------
      s = el.attr("ng-show");
      if (s) {
        try {
          if (geval(s)) {
            //el.show();
            // NOTE: Do not use .show() since jQuery (as at version first developed) would not retain 'flex' of any class
            el.css("display", "");
            el.css("visibility", "");
          }
          else {
            el.hide();
          }
        }
        catch (ex) {
          console.warn("widget.UI.Evaluate: Failed to evaluate ng-show expression '" + s + "'.\n\n" + ex);
        }
      }

      // -------
      // ng-hide
      // -------
      s = el.attr("ng-hide");
      if (s) {
        try {
          if (geval(s)) {
            el.hide();
          }
          else {
            el.show();
          }
        }
        catch (ex) {
          console.warn("widget.UI.Evaluate: Failed to evaluate ng-hide expression '" + s + "'.\n\n" + ex);
        }
      }

      // -----
      // ng-if
      // -----
      s = el.attr("ng-if");
      if (s) {
        try {
          if (geval(s)) {
            // Leave
          }
          else {
            el.remove();
          }
        }
        catch (ex) {
          console.warn("widget.UI.Evaluate: Failed to evaluate ng-if expression '" + s + "'.\n\n" + ex);
        }
      }

      // -------
      // ng-bind
      // -------
      s = el.attr("ng-bind");
      if (s) {
        try {
          s = geval(s);
          if (s === undefined) {
            s = "";
          }

          // Format
          var format;
          try {
            format = el.attr("ng-bind-format") || "";
            switch (format.toLowerCase()) {
              case "":
              case "string":
                break;

              case "currency":
                s = Runtime_FormatCurrency(s);
                break;

              case "currency$":
                s = Runtime_FormatCurrency(s, true);
                break;

              case "date":
                s = Runtime_FormatDate(s);
                break;

              default:
                console.warn("widget.UI.Evaluate: Unrecognised ns-bind-format '" + format + "'.");
            }
          }
          catch (ex) {
            console.warn("widget.UI.Evaluate: Failed to evaluate ns-bind-format '" + format + "' for value '" + s + "'.\n\n" + ex);
          }

          el.html(HtmlEncode(s));
        }
        catch (ex) {
          console.warn("widget.UI.Evaluate: Failed to evaluate ng-bind expression '" + s + "'.\n\n" + ex);
        }
      }

      // ----------------------
      // ng-bind-attribute-name
      // ----------------------
      s = el.attr("ng-bind-attribute-name");
      if (s) {
        var s2 = el.attr("ng-bind-attribute-value");
        try {
          el.attr(s, geval(s2));
        }
        catch (ex) {
          console.warn("widget.UI.Evaluate: Failed to evaluate ng-bind-attribute-value expression '" + s2 + "'.\n\n" + ex);
        }
      }

      // ------------
      // ng-bind-html
      // ------------
      s = el.attr("ng-bind-html");
      if (s) {
        try {
          s = geval(s);
          if (s === undefined) {
            s = "";
          }

          el.html(s);
        }
        catch (ex) {
          console.warn("widget.UI.Evaluate: Failed to evaluate ng-bind-html expression '" + s + "'.\n\n" + ex);
        }
      }

      // --------
      // ng-class
      // --------
      s = el.attr("ng-class");
      if (s) {
        try {
          el.attr("class", geval(s));
        }
        catch (ex) {
          console.warn("widget.UI.Evaluate: Failed to evaluate ng-class expression '" + s + "'.\n\n" + ex);
        }
      }

      // ---------
      // ng-repeat
      // ---------
      s = el.attr("ng-repeat");
      if (s) {
        // Get filter
        var filter = el.attr("ng-repeat-filter");

        // Check template has been saved
        if (!el.prop("ng-repeat-template")) {
          el.prop("ng-repeat-template", el.html());
        }

        // Clear out child elements
        el.children().remove();

        // Get repeating template
        var template = el.prop("ng-repeat-template");

        // Validate
        var itemName = "", array = null, valid = true, n;
        if (valid) {
          if (s.startsWith("for ")) {
            itemName = s.substr(4);
            n = itemName.indexOf(" ");
            if (n != -1) itemName = itemName.substr(0, n);
          }
          else {
            valid = false;
          }
        }

        if (valid) {
          n = s.indexOf(" in ");
          if (n == -1) {
            valid = false;
          }
          else {
            array = s.substr(n + 4);
          }
        }

        if (valid && (!itemName || !array)) valid = false;

        // Execute
        if (valid) {
          try {
            var arr = geval(array);

            // Get filtered array
            if (filter) {
              var arr2 = [];

              // Set loop variable 
              for (var j = 0; j < arr.length; j++) {
                window[itemName] = arr[j];
                if (geval(filter)) arr2.push(arr[j]);
              }

              // Finalise
              arr = arr2;
            }

            // Iterate
            for (var j = 0; j < arr.length; j++) {
              // Set Angular-style variable names
              window.$index = j;
              window.$first = ($index == 0);
              window.$last = ($index == arr.length - 1);
              window.$middle = (!window.$first && !window.$last);

              // Set loop variable
              window[itemName] = arr[j];

              // Create item element
              var eli = $(template);
              var parent = $("<div></div>");
              parent.append(eli);
              Evaluate(parent);
              el.append(eli);
            }
          }
          catch (ex) {
            console.warn("widget.UI.Evaluate: Failed to iterate array variable '" + array + "' in ng-repeat expression '" + s + "'.\n\n" + ex);
          }
        }
        else {
          console.warn("widget.UI.Evaluate: ng-repeat format of '" + s + "' is incorrect. It should be 'for loopVariableName in array'.");
        }
      }
    }
  }



  // =======================
  // PUBLIC: Calendar object
  // =======================
  Calendar = function (e, options) {

    var mCalendarDay = new Date().getDate();
    var mCalendarMonth = new Date().getMonth();
    var mCalendarYear = new Date().getFullYear();
    var mCalendarStartDate;
    var mCellValues = new Array(42);
    var mElement;
    var mElementCells = new Array(42);
    var mElementFooter;
    var mElementMonth;
    var mElementResizeSelect;
    var mElementYear;
    var mMarkers = null;
    var mInitialised = false;
    var mOptions;
    var mValue;
    var mValueOriginal;

    // Extend options with defaults
    CalendarDefaults = {
      width: "auto",

      readOnly: false,
      autoReadOnly: true,

      showButtons: false,
      showValue: true, // When not being used to select a date, this will hide the current value
      valueBorderOnly: false,

      onCellDblClick: null,
      onChange: null,

      // Friend
      standalone: true, // Behaves slightly differently to when used by DateBox (added so as not to break compatibility)
    };
    mOptions = $.extend({}, CalendarDefaults, options);

    // Default Value
    mValue = Runtime_ParseDate("Now", false, false);
    mValueOriginal = new Date(mValue.valueOf());

    // Get Element and validate (may be element or id)
    // NOTE: Typically, you would attach a Calendar to a div element
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.Calendar: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Allow focus (i.e., so we can handle key presses etc)
    mElement.attr("tabindex", "-1");

    // Tweak element
    mElement.addClass("is-no-select");

    // Handle events
    // NOTE: Handled in UpdateElement

    // Initialise
    UpdateElement(true);


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement(initialise) {
      // Initialise (i.e., create elements)?
      if (initialise) {
        // Flag
        mInitialised = true;

        // Clear
        mElement.children().remove();

        // Create header
        var header = $("<div class='is-calendar-header'></div>");
        //mElement.append(header);

        // Header controls
        var wrapperMonthYear = $("<div class='month-year'></div>");
        var leftMonth = $("<div class='left month' title='Back a month'/>");

        mElementMonth = $("<select class='month'></select>");
        for (var i = 0; i < 12; i++) {
          mElementMonth.append("<option>" + Runtime_GetMonthName(i) + "</option>");
        }

        mElementYear = $("<select class='year'></select>");
        for (var i = 0; i < 200; i++) {
          mElementYear.append("<option>" + (1900 + i) + "</option>");
        }

        var rightMonth = $("<div class='right month' title='Forward a month'/>");
        wrapperMonthYear.append(leftMonth);
        wrapperMonthYear.append(mElementMonth);
        wrapperMonthYear.append(mElementYear);
        wrapperMonthYear.append(rightMonth);
        header.append(wrapperMonthYear);

        // Create body
        var body = $("<div class='is-calendar-body'></div>");

        // Create table
        var table = $("<table style='width:100%'><thead><tr></tr></thead><tbody></tbody></table>");
        body.append(table);

        // Cell headings (days of week)
        var headingRow = $(">thead>tr", table);
        for (var x = 0; x < 7; x++) {
          var th = $("<th>" + Runtime_GetDayOfWeekName(x).substr(0, 3) + "</th>");
          if (x == 0 || x == 6) th.addClass("weekend");

          // Add
          headingRow.append(th);
        }

        // Day cells (7 x 6)
        var tbody = $(">tbody", table);
        for (var y = 0; y < 6; y++) {
          // Create row
          var row = $("<tr></tr>");

          // Add cells
          for (var x = 0; x < 7; x++) {
            var td = $("<td></td>");
            mElementCells[x + y * 7] = td;

            if (x == 0 || x == 6) td.addClass("weekend");

            // Add
            row.append(td);
          }

          // Add row
          tbody.append(row);
        }

        // Handle events
        mElementYear.bind("change", function (e) {
          // Set calendar year and refresh
          mCalendarYear = parseInt(mElementYear.val());
          if (mOptions.standalone) {
            // Don't actually change value
            UpdateElement(false);
          }
          else {
            // Change value
            ReformValueFromDropdowns();
            NotifyChange(false);
          }

          // Focus element
          mElement.focus();
          mElement.select();
        });
        mElementMonth.bind("change", function (e) {
          // Set calendar month and refresh
          mCalendarMonth = mElementMonth[0].selectedIndex;
          if (mOptions.standalone) {
            // Don't actually change value
            UpdateElement(false);
          }
          else {
            // Change value
            ReformValueFromDropdowns();
            NotifyChange(false);
          }

          // Focus element
          mElement.focus();
          mElement.select();
        });
        leftMonth.bind("click", function (e) {
          // Set calendar month and refresh
          mCalendarMonth -= 1;
          if (mCalendarMonth < 0) {
            mCalendarMonth = 11;
            mCalendarYear -= 1;
          }
          if (mOptions.standalone) {
            // Don't actually change value
            UpdateElement(false);
          }
          else {
            // Change value
            ReformValueFromDropdowns();
            NotifyChange(false);
          }
        });

        rightMonth.bind("click", function (e) {
          // Set calendar month and refresh
          mCalendarMonth += 1;
          if (mCalendarMonth > 11) {
            mCalendarMonth = 0;
            mCalendarYear += 1;
          }
          if (mOptions.standalone) {
            // Don't actually change value
            UpdateElement(false);
          }
          else {
            // Change value
            ReformValueFromDropdowns();
            NotifyChange(false);
          }
        });

        $("td", table).bind("click", function (e) {
          if (!mOptions.readOnly) {
            // Get cell offset
            var i = parseInt($(e.delegateTarget).attr("dateOffset"));

            // Update value
            var ValueNew = new Date(mCalendarStartDate.getFullYear(), mCalendarStartDate.getMonth(), mCalendarStartDate.getDate() + i);
            if (mValue === null || mValue.valueOf() != ValueNew.valueOf()) {
              mValue = ValueNew;
              UpdateElement(false);

              // Notify
              NotifyChange();
            }
          }
        });

        if (mOptions.onCellDblClick) {
          $("td", table).bind("dblclick", function (e) {
            mOptions.onCellDblClick(_self, {});
          });
        }

        // Create footer
        mElementFooter = $("<div class='is-calendar-footer'></div>");

        // Footer controls
        var footerClear = $("<button>Clear</button>");
        footerClear.on("click", function () {
          Value(null);
          UpdateElement(false);
          NotifyChange();
        });

        var footerToday = $("<button>Today</button>");
        footerToday.on("click", function () {
          var d = new Date();
          Value(new Date(d.getFullYear(), d.getMonth(), d.getDate()));
          UpdateElement(false);
          GotoValue();
          NotifyChange();
        });

        var footerMinus1W = $("<button>-Week</button>");
        footerMinus1W.on("click", function () {
          if (!mValue) mValue = new Date().Date();
          mValue = new Date(mValue.getFullYear(), mValue.getMonth(), mValue.getDate() - 7);
          UpdateElement(false);
          GotoValue();
          mElement.focus();
          mElement.select();
          NotifyChange(false);
        });

        var footerPlus1W = $("<button>+Week</button>");
        footerPlus1W.on("click", function () {
          if (!mValue) mValue = new Date().Date();
          mValue = new Date(mValue.getFullYear(), mValue.getMonth(), mValue.getDate() + 7);
          UpdateElement(false);
          GotoValue();
          mElement.focus();
          mElement.select();
          NotifyChange(false);
        });

        var footerAccept = $("<button class='ok'>Done</button>");
        footerAccept.on("click", function () {
          //Value(new Date(mCalendarYear, mCalendarMonth, mCalendarDay));
          UpdateElement(false);
          NotifyChange();
        });

        if (!mOptions.showValue) {
          footerClear.hide();
          footerMinus1W.hide();
          footerPlus1W.hide();
        }
        if (mOptions.standalone) {
          footerAccept.hide();
        }

        mElementFooter.append(footerClear);
        mElementFooter.append(footerMinus1W);
        mElementFooter.append(footerToday);
        mElementFooter.append(footerPlus1W);
        mElementFooter.append(footerAccept);

        // Append Header, Body and Footer to Element (performance enhancement for IE)
        mElement.append(header);
        mElement.append(body);
        mElement.append(mElementFooter);
      }

      // Set Weekday caption
      //mElementDayName.text(Runtime_GetDayOfWeekName(new Date(mCalendarYear, mCalendarMonth, mCalendarDay).getDay()));

      // Set Calendar Day, Month and Year dropdowns
      mElementYear.val(mCalendarYear + "");
      mElementMonth.val(Runtime_GetMonthName(mCalendarMonth));
      //mElementDay.val(mCalendarDay);

      // Footer
      if (mOptions.readOnly || !mOptions.showButtons) mElementFooter.hide(); else mElementFooter.show();

      // Find calendar start date (must be a Sunday so work backwards if necessary)
      mCalendarStartDate = new Date(mCalendarYear, mCalendarMonth);
      while (mCalendarStartDate.getDay() != 0) {
        mCalendarStartDate.setDate(mCalendarStartDate.getDate() - 1);
      }

      // Day cell values
      var tempDate = new Date(mCalendarStartDate.valueOf());
      var today = new Date();
      for (var i = 0; i < 42; i++) {
        var c = mElementCells[i];

        // Update cell
        c.text(tempDate.getDate());
        c.attr("dateOffset", i);

        c.removeClass("is-selectable notcurrent today is-sel is-sel-border");
        c.attr("title", null);
        if (!mOptions.readOnly) c.addClass("is-selectable");
        if (tempDate.getMonth() != mCalendarMonth) c.addClass("notcurrent");
        if (tempDate.getFullYear() == today.getFullYear() && tempDate.getMonth() == today.getMonth() && tempDate.getDate() == today.getDate()) {
          c.addClass("today");
          c.attr("title", "Today");
        }

        // Selected date?
        if (mValue != null && mOptions.showValue) {
          //if (tempDate.getFullYear() == mValue.getUTCFullYear() && tempDate.getMonth() == mValue.getUTCMonth() && tempDate.getDate() == mValue.getUTCDate()) {
          if (tempDate.getFullYear() == mValue.getFullYear() && tempDate.getMonth() == mValue.getMonth() && tempDate.getDate() == mValue.getDate()) {
            if (mOptions.valueBorderOnly) {
              c.addClass("is-sel-border");
            }
            else {
              c.addClass("is-sel");
            }
          }
        }

        // Markers
        if (mMarkers) {
          c.attr("style", "");
          c.attr("title", "");

          for (var j = 0; j < mMarkers.length; j++) {
            var item = mMarkers[j];
            var value = item.value

            if (item.value && item.value.getFullYear) {
              if (tempDate.getFullYear() == value.getFullYear() && tempDate.getMonth() == value.getMonth() && tempDate.getDate() == value.getDate()) {
                //c.addClass("is-sel");
                if (item.colour) c.css("background-color", item.backgroundColour);
                if (item.backgroundColour) c.css("color", item.colour);
                if (item.tooltipText) c.attr("title", item.tooltipText);
              }
            }
            else {
              // Invalid
            }
          }
        }

        mCellValues[i] = tempDate;

        tempDate.setDate(tempDate.getDate() + 1);
      }

      // CSS Classes
      mElement.addClass("is-calendar");

      // FUDGE: IE and iOS don't align text in Select elements so resize to fit content!
      var t = window.setTimeout(function () {
        ResizeSelect(mElementMonth);
        ResizeSelect(mElementYear);

        window.clearTimeout(t);
        t = null;
      }, 10);

      // Other
    }

    // -------------------------------------------------------
    // PRIVATE: Resize a Select Element to fit selected option
    // -------------------------------------------------------
    function ResizeSelect(select) {
      // Initialise
      if (!mElementResizeSelect) {
        mElementResizeSelect = $("<select style='position:fixed; left:-1000px; top:-1000px' tabindex='-1' />");
        mElement.append(mElementResizeSelect);
      }
      mElementResizeSelect.children().remove();

      // Add current value
      mElementResizeSelect.append("<option>" + widget.UI.HtmlEncode(select.val()) + "</option>");

      // Position so font size etc are inherited
      select.after(mElementResizeSelect);
      mElementResizeSelect.attr("class", select.attr("class"));

      // Get width
      var w = mElementResizeSelect.width() + 4;

      // Apply
      if (w) select.css("width", w + "px");
    }

    // ----------------------------------------------
    // PRIVATE: Reform the Value from D/M/Y dropdowns
    // ----------------------------------------------
    function ReformValueFromDropdowns() {
      if (!mValue) {
        // No value so assume the current day of the month
        mValue = new Date(mCalendarYear, mCalendarMonth, mCalendarDay);
      }
      else {
        mValue = new Date(mCalendarYear, mCalendarMonth, mValue.getDate());
      }
      //mValue = new Date(mCalendarYear, mCalendarMonth, mCalendarDay);
      UpdateElement(false);
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange(closeDropdown) {
      // Notify
      var e = { ChangeHandled: false, ValueOriginal: mValueOriginal, CloseDropdown: closeDropdown };
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset TextOriginal?
      if (e.ChangeHandled) {
        if (mValue)
          mValueOriginal = new Date(mValue.valueOf());
        else
          mValueOriginal = null;
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return mValue != mValueOriginal;
    }

    // --------------------------
    // PUBLIC: The jQuery Element
    // --------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // -------------------------------------------------------------
    // PUBLIC: Goto Value, i.e., ensure the current value is visible
    // -------------------------------------------------------------
    function GotoValue() {
      if (mValue instanceof Date) {
        mCalendarYear = mValue.getFullYear();
        mCalendarMonth = mValue.getMonth();
        mCalendarDay = mValue.getDate();
      }
      else {
        var d = new Date();
        mCalendarYear = d.getFullYear();
        mCalendarMonth = d.getMonth();
        mCalendarDay = d.getDate();
      }
      UpdateElement();
    }

    // ----------------------------------------------
    // PUBLIC: Goto a Date without changing the Value
    // ----------------------------------------------
    function GotoDate(value) {
      if (value instanceof Date) {
        if (isNaN(value.valueOf())) {
          // Invalid date
        }
        else {
          mCalendarYear = value.getFullYear();
          mCalendarMonth = value.getMonth();
          mCalendarDay = value.getDate();
        }
      }
      UpdateElement(false);
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        return mValue;
      }
      else {
        // Set
        if (value === null) {
          mValue = null;
          mValueOriginal = value;
        }
        else if (value instanceof Date) {
          mValue = value;
          mValueOriginal = value;
        }
        else {
          //window.alert(value);
          console.warn("Attempted to set ISCalendar value to a value that is not a Date or null.");
        }
        UpdateElement();

        // Ensure date is showing
        if (mValue != null) GotoValue();
      }
    }

    // ================================
    // Public: Set the array of Markers
    // ================================
    function MarkersSet(value) {
      mMarkers = value;
      UpdateElement();
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "Calendar",

      Changed: Changed,
      Element: Element,
      Focus: Focus,
      GotoDate: GotoDate,
      GotoValue: GotoValue,
      MarkersSet: MarkersSet,
      ReadOnly: ReadOnly,
      Value: Value
    };
    return _self;
  };



  // ============================================
  // PUBLIC: AccountIncomingPaymentDetails object
  // ============================================
  function AccountIncomingPaymentDetails(e, options) {

    var mAccountId;
    var mDefaultValuesOnPaymentMethodChange = false;
    var mElement;
    var mInitialised = false;
    var mIsNewAccountWizard = false;
    var mIsAccountPaymentDetailsWizard = false;
    var mIsPaymentWizard = false;
    var mOptions;
    var mPaymentTypeCategoryFilter = "";
    var mPaymentMethods;
    var mPaymentMethodsFiltered;
    var mRecord;
    var mTransactionDate = null;
    var mWarningMessage = "";
    var mWarningTimer;

    var C = {
      trPaymentMethod: null,
      cmdExistingDetailsLookup: null,
      cboPaymentMethod: null,

      trAccountSortCode: null,
      cboAccountSortCode: null,

      trAccountNumber: null,
      txtAccountNumber: null,

      trName: null,
      txtName: null,

      trCardExpiry: null,
      cboCardExpiryMonth: null,
      cboCardExpiryYear: null,
      txtCardSecurityCode: null,

      trExternalIdCombo: null,
      cboExternalIdCombo: null,

      trOpenAgreement: null,
      cmdOpenAgreement: null,

      trReference: null,
      divReferenceTagsList: null,
      txtReference1: null,
      txtReference2: null,
      txtReference3: null,

      trAccountEmail: null,
      cboAccountEmail: null,
      trExternalId: null,
      txtExternalId: null,      
      trDescription: null,
      txtDescription: null,

      trCashRegister: null,
      cboCashRegister: null,

      trWarning: null,
      divWarning: null,
    };

    // Extend options with defaults
    AccountPaymentDetailsDefaults = {
      allowBlank: false,
      readOnly: false,
      autoReadOnly: true,
      visible: true,

      paymentEntry: false, // Show fields specific to making a payment (rather than just recording banking details)
      historic: false, // Affects how list of Credit Card Expiry Years is built
      resolveReference: false, // Resolve reference tags, e.g., for Payment Entry

      showCashRegister: false,
      showExistingDetailsLookup: true, // Show a button that looks up existing Payment Details, e.g., those defined on the Account Clients

      paymentMethodVisible: true, // Ways to restrict the control, e.g., when using in a Client Portal
      paymentMethodReadOnly: false,

      cashRegisterReadOnly: false,

      hideSplitAddButton: false, // Determines if the Add Contact button for Zepto should not be displayed

      onPaymentMethodChange: null,
    };
    mOptions = $.extend({}, AccountPaymentDetailsDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.AccountIncomingPaymentDetails: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Validate Element
    switch (mElement.prop("tagName")) {
      case "TBODY":
        break;

      default:
        console.warn("widget_ui.AccountIncomingPaymentDetails: Element '" + id + "' must be a TBODY element.");
        return;
    }

    // Create sub-elements and controls
    //   Payment Method
    var cid = CreateGuid(true);
    C.trPaymentMethod = $("<tr style='display:none'><th><label for='" + cid + "'>Method:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trPaymentMethod);
    C.cboPaymentMethod = DBCombo($("input", C.trPaymentMethod), {
      allowBlank: mOptions.allowBlank,
      limitToList: true,
      maxLength: 10,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
        if (C.cboPaymentMethod.Text() && mDefaultValuesOnPaymentMethodChange) {
          LoadAccountDetailsSmart();
        }

        // Notify
        var e = {};
        if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_self, e);
      },
    });
    //   Lookup Existing
    C.cmdExistingDetailsLookup = $("<button tabindex='-1' class='is-button small' style='margin-left:4px' icon='Find' title='Lookup banking details from this Account and its Clients'>Lookup</button>");
    $("label.is-combobox", C.cboPaymentMethod.WrapperElement()).before(C.cmdExistingDetailsLookup);
    C.cmdExistingDetailsLookup.on("click", BankingDetailsLookup);
    ApplyIcons(C.cmdExistingDetailsLookup);
    //    Account Sort Code
    cid += "X";
    C.trAccountSortCode = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Sort Code:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountSortCode);
    C.cboAccountSortCode = DBCombo($("input", C.trAccountSortCode), {
      allowBlank: false,
      maxLength: 10,
      width: "8em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    //    Account Number/ Credit Card Number
    cid += "X";
    C.trAccountNumber = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Account No.:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountNumber);
    C.txtAccountNumber = TextBox($("input", C.trAccountNumber), {
      allowBlank: false,
      maxLength: 30,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    //    Name
    cid += "X";
    C.trName = $("<tr style='display:none'><th><label for='" + cid + "'>Name:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trName);
    C.txtName = TextBox($("input", C.trName), {
      allowBlank: true,
      maxLength: 100,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    //    Card Expiry + Card Security Code
    cid += "X";
    C.trCardExpiry = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Card Expiry:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/> <input id='" + cid + "2'/>  <input id='" + cid + "3'/></td>");
    mElement.append(C.trCardExpiry);
    C.cboCardExpiryMonth = ComboBox($($("input", C.trCardExpiry)[0]), {
      allowBlank: true,
      listCsv: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
      limitToList: false,
      maxLength: 3,
      width: "4em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.cboCardExpiryMonth.Element().blur(function () {
      // Allow month to be entered as a numeric value
      if (C.cboCardExpiryMonth.Text()) {
        var month = Runtime_ParseNumber(C.cboCardExpiryMonth.Text());
        if (month > 0) {
          // Convert to list value
          C.cboCardExpiryMonth.ListIndex(month - 1);
        }
        else {
          // Limit to list
          if (!C.cboCardExpiryMonth.ListExists(C.cboCardExpiryMonth.Text())) {
            C.cboCardExpiryMonth.Text("");
          }
        }
      }
    });
    C.cboCardExpiryYear = ComboBox($($("input", C.trCardExpiry)[1]), {
      allowBlank: true,
      limitToList: false,
      maxLength: 4,
      width: "5em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.cboCardExpiryYear.Element().blur(function () {
      // Allow 2-digit year entry
      if (C.cboCardExpiryYear.Text()) {
        var year = Runtime_ParseNumber(C.cboCardExpiryYear.Text());
        if (year < 100) year += 2000;
        if (year > 9999) year = 9999;
        C.cboCardExpiryYear.Text(year);
      }
    });
    var arrYears = [];
    var start = new Date().getFullYear(), end = start + 10;
    if (mOptions.historic) start -= 10;
    for (var i = start; i < end; i++) {
      arrYears.push(i + "");
    }
    C.cboCardExpiryYear.ListFromArray(arrYears);
    //    Card Security Code
    C.txtCardSecurityCode = TextBox($($("input", C.trCardExpiry)[2]), {
      allowBlank: false,
      maxLength: 10,
      width: "7em",
    });

    //   PayTo
    cid += "X";
    C.trExternalIdCombo = $("<tr style='display:none'><th><label for='" + cid + "'>Agreement&nbsp;ID:&nbsp;</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trExternalIdCombo);
    C.cboExternalIdCombo = DBCombo($("input", C.trExternalIdCombo), {
      limitToList: false,
      maxLength: 50,
      width: "20em",
      
      onChange: cboExternalIdCombo_OnChange,
    });

    cid += "X";
    C.trOpenAgreement = $("<tr style='display:none'><th></th><td><button id='" + cid + "' class='is-button small'>Open Agreement</button></td>");
    mElement.append(C.trOpenAgreement);
    C.cmdOpenAgreement = $("button", C.trOpenAgreement);
    C.cmdOpenAgreement.click(PayToOpenAgreement)

    //    Reference
    cid += "X";
    C.trReference = $("<tr style='display:none'><th><label for='" + cid + "P'>Reference:</label></th><td><div id='" + cid + "TL'></div><input id='" + cid + "P'/> <input id='" + cid + "C'/> <input id='" + cid + "R'/></td>");
    mElement.append(C.trReference);
    C.divReferenceTagsList = $("div", C.trReference);
    C.txtReference1 = TextBox($($("input", C.trReference)[0]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.txtReference2 = TextBox($($("input", C.trReference)[1]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.txtReference3 = TextBox($($("input", C.trReference)[2]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });

    //    Zepto
    cid += "X";
    C.trAccountEmail = $("<tr style='display:none'><th><label for='" + cid + "'>Email:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountEmail);
    C.cboAccountEmail = ComboBox($("input", C.trAccountEmail), {
      allowBlank: true,
      maxLength: 255,
      width: "100%",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    cid += "X";
    C.trAccountPhone = $("<tr style='display:none'><th><label for='" + cid + "'>Phone:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountPhone);
    C.cboAccountPhone = ComboBox($("input", C.trAccountPhone), {
      allowBlank: true,
      maxLength: 255,
      width: "100%",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    cid += "X";
    C.trExternalId = $("<tr style='display:none'><th><label for='" + cid + "'>Contact ID:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trExternalId);
    C.txtExternalId = TextBox($("input", C.trExternalId), {
      allowBlank: true,
      maxLength: 50,

      onButtonClick: txtExternalId_ButtonClick,
      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    var buttons = [];
    buttons.push({ id: "Add", tooltipText: "Add", icon: "Add" });
    buttons.push({ id: "Verify", tooltipText: "Verify", icon: "Check" });
    C.txtExternalId.ButtonsDefine(buttons);    

    cid += "X";
    C.trDescription = $("<tr style='display:none'><th><label for='" + cid + "'>Description:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trDescription);
    C.txtDescription = TextBox($("input", C.trDescription), {
      allowBlank: true,
      maxLength: 280,
      multiLine: true,
      rows: 3,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });

    //    Cash Register
    cid += "X";
    C.trCashRegister = $("<tr style='display:none'><th><label for='" + cid + "'>Cash&nbsp;Register:&nbsp;</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trCashRegister);
    C.cboCashRegister = DBCombo($("input", C.trCashRegister), {
      allowBlank: true,
      maxLength: 10,
      width: widget.UI.FIELD_WIDTH_CODE_10,
    });
    //    Warning
    cid += "X";
    C.trWarning = $("<tr style='display:none'><th colspan='2'><div class='is-info-text info' style='color:darkred; margin-bottom:0 !important; margin-top:0 !important; width:100%'></div></th>");
    mElement.append(C.trWarning);
    C.divWarning = $("div", C.trWarning);

    // Update element
    UpdateElement(false);


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement(refetchWarningMessage) {
      // Initialise
      if (mWarningTimer && (refetchWarningMessage || !C.cboPaymentMethod.Text())) {
        window.clearTimeout(mWarningTimer);
        mWarningTimer = null;
      }

      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }

      // Layout and Configuration
      // NOTE: Do not arbitrarily hide controls since they lose focus!
      if (!mInitialised) C.trPaymentMethod.hide();
      if (!mWarningMessage || !C.cboPaymentMethod.Text()) C.trWarning.hide();

      if (mInitialised) {
        // Layout
        if (!mOptions.readOnly && !mOptions.paymentMethodReadOnly && mOptions.showExistingDetailsLookup && (mAccountId || mClientIds)) {
          C.cmdExistingDetailsLookup.show();
        }
        else {
          C.cmdExistingDetailsLookup.hide();
        }

        if (mOptions.paymentMethodVisible) {
          C.trPaymentMethod.show();
        }
        else {
          C.trPaymentMethod.hide();
        }
        var paymentTypeCategory = "";
        var paymentMethod = null;
        if (C.cboPaymentMethod.ListIndex() != -1) {
          paymentMethod = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()];
          paymentTypeCategory = paymentMethod.PaymentTypeCategory;
        }
        else if (C.cboPaymentMethod.Text()) {
          C.cboPaymentMethod.Text("");
        }

        // Account Sort Code
        if (mRecord && mRecord.BankSortCodeCaption) {
          if (mRecord.ShowFullAccountSortCodeList) {
            C.cboAccountSortCode.ShowDropdown(true);
            C.cboAccountSortCode.RefreshFromStandardRange("BankBranches");
          }
          else {
            C.cboAccountSortCode.ShowDropdown(false);
          }
        }

        // Card Security Code
        var CardSecurityCodeRequired = paymentMethod && paymentMethod.CscRequired;
        if (paymentMethod) C.txtCardSecurityCode.BlankTip(paymentMethod.CscDescription);

        switch (paymentTypeCategory.toUpperCase()) {
          case "":
            // Unknown
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();
            break;

          case "BANK":
            // Bank Account
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.cboAccountSortCode.Caption(mRecord.BankSortCodeCaption + ":");
              C.trAccountSortCode.show();
            }
            else {
              C.trAccountSortCode.hide();
            }

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.show();

            if (mRecord) C.txtReference1.BlankTip(mRecord.Reference1Caption);
            if (mRecord) C.txtReference1.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(mRecord && mRecord.Reference1Caption);

            if (mRecord) C.txtReference2.BlankTip(mRecord.Reference2Caption);
            if (mRecord) C.txtReference2.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference2.WidthResizeFromParent();
            C.txtReference2.Visible(mRecord && mRecord.Reference2Caption != null);

            if (mRecord) C.txtReference3.BlankTip(mRecord.Reference3Caption);
            if (mRecord) C.txtReference3.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference3.WidthResizeFromParent();
            C.txtReference3.Visible(mRecord && mRecord.Reference3Caption != null);

            if (mRecord.Reference1Caption && mRecord.Reference2Caption) {
              C.txtReference1.Caption("References:");
            }
            else {
              C.txtReference1.Caption("Reference:");
              C.txtReference1.BlankTip("");
            }
            C.cboAccountSortCode.AllowBlank(!paymentMethod.HasExportService);
            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);
            break;

          case "CASH":
            // Cash
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            if (mOptions.showCashRegister && paymentMethod.IsCashRegisterUsed) {
              C.trCashRegister.show();
              C.cboCashRegister.AllowBlank(!paymentMethod.IsCashRegisterRequired);
            }
            else {
              C.trCashRegister.hide();
            }
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();
            break;

          case "CHEQUE":
            // Cheque
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            if (mOptions.showCashRegister && paymentMethod.IsCashRegisterUsed) {
              C.trCashRegister.show();
              C.cboCashRegister.AllowBlank(!paymentMethod.IsCashRegisterRequired);
            }
            else {
              C.trCashRegister.hide();
            }
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();

            C.trName.show();
            C.txtName.Caption("Drawer:");
            C.txtName.WidthResizeFromParent();

            if (mOptions.paymentEntry) {
              C.txtName.AllowBlank(!paymentMethod.HasExportService);
            }
            else {
              C.txtName.AllowBlank(true);
            }
            break;

          case "CREDITCARD":
            // Credit Card
            C.trAccountSortCode.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Card No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Card Name:");
            C.txtName.WidthResizeFromParent();

            C.trCardExpiry.show();
            C.txtCardSecurityCode.Visible(CardSecurityCodeRequired);

            C.trReference.show();
            C.txtReference1.BlankTip("");
            C.txtReference1.Caption("Reference:");
            C.txtReference1.MaxLength(50);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(true);
            C.txtReference2.Visible(false);
            C.txtReference3.Visible(false);

            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(true);
            C.cboCardExpiryMonth.AllowBlank(!paymentMethod.HasExportService);
            C.cboCardExpiryYear.AllowBlank(!paymentMethod.HasExportService);
            break;

          case "MONOOVA":
            // Monoova
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountPhone.hide();
            C.trAccountEmail.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.cboAccountSortCode.AllowBlank(false);
              C.cboAccountSortCode.Caption(mRecord.BankSortCodeCaption + ":");
              C.trAccountSortCode.show();
            }
            else {
              C.trAccountSortCode.hide();
            }            

            C.trAccountNumber.show();
            C.txtAccountNumber.AllowBlank(false);
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);
            C.txtName.Caption("Name:")            
            C.txtName.WidthResizeFromParent();    

            C.trReference.show();
            C.txtReference2.Visible(false);
            C.txtReference3.Visible(false);

            C.txtReference1.Visible(true);
            C.txtReference1.AllowBlank(true);
            C.txtReference1.BlankTip("");
            C.txtReference1.MaxLength(18);
            C.txtReference1.WidthResizeFromParent();
            break;

          case "POSCARD":
            // POS Card
            C.trAccountSortCode.hide();
            C.trReference.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Card No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Card Name:");
            C.txtName.WidthResizeFromParent();

            C.trCardExpiry.show();
            C.txtCardSecurityCode.Visible(CardSecurityCodeRequired);

            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);
            C.cboCardExpiryMonth.AllowBlank(!paymentMethod.HasExportService);
            C.cboCardExpiryYear.AllowBlank(!paymentMethod.HasExportService);
            break;

          case "SPLIT":          
            // Zepto (formally Split Payments)
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountPhone.hide();

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.cboAccountSortCode.Caption(mRecord.BankSortCodeCaption + ":");
              C.trAccountSortCode.show();
            }
            else {
              C.trAccountSortCode.hide();
            }

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.hide();

            C.cboAccountSortCode.AllowBlank(false);
            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);

            C.trAccountEmail.show();
            C.trExternalId.show();
            C.txtExternalId.WidthResizeFromParent();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();
            break;

          case "PAYTO":
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.show();
            C.cboExternalIdCombo.WidthResizeFromParent();
            C.cboExternalIdCombo.RefreshFromCodeDescriptionList(paymentMethod.BankingPayToItems, "Code", "Description");
            C.cboExternalIdCombo.AllowBlank(!mOptions.paymentEntry || mOptions.allowBlank);
            cboExternalIdCombo_OnChange();

            C.trReference.show();
            C.txtReference1.Visible(true);
            C.txtReference1.Caption("Reference:");
            C.txtReference1.AllowBlank(true);
            C.txtReference1.MaxLength(35);
            C.txtReference1.WidthResizeFromParent();

            C.txtReference2.Visible(false);
            C.txtReference3.Visible(false);

            C.trDescription.show();
            break;

          case "ZEPTONZ":
            // Zepto NZ
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountSortCode.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.hide();

            C.cboAccountSortCode.AllowBlank(false);
            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);

            C.trAccountEmail.show();
            C.trAccountPhone.show();
            C.trExternalId.show();
            C.txtExternalId.WidthResizeFromParent();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();
            break;

          case "TOKEN":
            // Token (like Bank Account but without the same validation)
            C.trAccountSortCode.hide();
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Token:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.show();

            if (mRecord) C.txtReference1.BlankTip(mRecord.Reference1Caption);
            if (mRecord) C.txtReference1.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(mRecord && mRecord.Reference1Caption);

            if (mRecord) C.txtReference2.BlankTip(mRecord.Reference2Caption);
            if (mRecord) C.txtReference2.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference2.WidthResizeFromParent();
            C.txtReference2.Visible(mRecord && mRecord.Reference2Caption != null);

            if (mRecord) C.txtReference3.BlankTip(mRecord.Reference3Caption);
            if (mRecord) C.txtReference3.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference3.WidthResizeFromParent();
            C.txtReference3.Visible(mRecord && mRecord.Reference3Caption != null);

            if (mRecord.Reference1Caption && mRecord.Reference2Caption) {
              C.txtReference1.Caption("References:");
            }
            else {
              C.txtReference1.Caption("Reference:");
              C.txtReference1.BlankTip("");
            }

            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(true);
            break;

          default:
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            C.trExternalIdCombo.hide();
            C.trOpenAgreement.hide();
            C.trDescription.hide();
            window.alert("Unhandled Payment Type Category '" + paymentTypeCategory + "'.");
        }

        // Other
        if (mRecord) {
        }

        // Cash Register
        if (mOptions.showCashRegister && paymentMethod && paymentMethod.IsCashRegisterUsed) {
          if (!C.cboCashRegister.__Refreshed) {
            C.cboCashRegister.RefreshFromStandardRange("CashRegisters");
            C.cboCashRegister.__Refreshed = true;
          }
        }

        // Read-Only
        C.cboPaymentMethod.ReadOnly(mOptions.readOnly || mOptions.paymentMethodReadOnly);
        C.cboAccountSortCode.ReadOnly(mOptions.readOnly);
        C.txtAccountNumber.ReadOnly(mOptions.readOnly);
        C.txtName.ReadOnly(mOptions.readOnly);
        C.cboCardExpiryMonth.ReadOnly(mOptions.readOnly);
        C.cboCardExpiryYear.ReadOnly(mOptions.readOnly);
        C.txtCardSecurityCode.ReadOnly(mOptions.readOnly);
        C.txtReference1.ReadOnly(mOptions.readOnly);
        C.txtReference2.ReadOnly(mOptions.readOnly);
        C.txtReference3.ReadOnly(mOptions.readOnly);
        C.cboCashRegister.ReadOnly(mOptions.readOnly || mOptions.cashRegisterReadOnly);        

        // Buttons
        C.txtExternalId.Buttons().ButtonVisible("Add", !mOptions.hideSplitAddButton);
        C.txtExternalId.Buttons().ButtonVisible("Verify", C.txtExternalId.Text() != "");

        // Warning
        // NOTE: Also updates Account Number and Sort Code formats if necessary
        if (refetchWarningMessage && mRecord && C.cboPaymentMethod.Text()) {
          mWarningTimer = window.setTimeout(function () {
            window.clearTimeout(mWarningTimer);
            mWarningTimer = null;

            // Fetch warning
            var params = { bankingDetailsJson: ToBankingDetailsJson() };
            if (mAccountId) params.AccountId = mAccountId;
            if (mTransactionDate) params.TransactionDate = mTransactionDate;

            widget._SystemGetString("AccountPaymentDetails_GetValidationDetails", params,
              function (data) {
                if (data) {
                  // Parse
                  data = JSON.parse(data);
                  mWarningMessage = data.Message;

                  // Format Account Number and Sort Code
                  if (!mOptions.readOnly) {
                    if (C.txtAccountNumber.Text() && C.txtAccountNumber.Text() == data.AccountNumberOriginal && data.AccountNumberFormatted) {
                      C.txtAccountNumber.Text(data.AccountNumberFormatted);
                    }

                    if (C.cboAccountSortCode.Text() && C.cboAccountSortCode.Text() == data.AccountSortCodeOriginal && data.AccountSortCodeFormatted) {
                      C.cboAccountSortCode.Text(data.AccountSortCodeFormatted);
                    }
                  }
                }
                else {
                  // Returned nothing!
                  mWarningMessage = "";
                }

                C.divWarning.html(HtmlEncode(mWarningMessage));
                if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
                if (data.Warning) C.divWarning.css("color", "darkred"); else C.divWarning.css("color", "green");
              },

              function (data) {
                mWarningMessage = data;
                widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: Failed to retrieve validation details: " + data);

                C.divWarning.html(HtmlEncode(mWarningMessage));
                if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
              }
            );
          }, 750);
        }
        else {
          if (C.cboPaymentMethod.Text()) {
            C.divWarning.html(HtmlEncode(mWarningMessage));
            if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
          }
        }
      }
      else {
        if (mWarningMessage) {
          C.divWarning.html(HtmlEncode(mWarningMessage));
        }
        else {
          C.divWarning.css("color", "darkred");
          C.divWarning.text("Initialising, please wait...");
        }
        C.trWarning.show();
      }
    }

    // ------------------
    // PUBLIC: Initialise
    // ------------------
    function Initialise(accountId, options, clientIds) {
      // Extend options with defaults
      var InitialiseDefaults = {
        applyDefaultPaymentMethod: false,
        applyDefaultCashRegister: false,

        branchId: "",

        defaultValuesOnPaymentMethodChange: false,
        skipLoadAccountDetailsSmart: false,

        isAccountPaymentDetailsWizard: false,
        isNewAccountWizard: false,        
        isPaymentWizard: false,
      };
      options = $.extend({}, InitialiseDefaults, options);

      // Initialise
      mAccountId = accountId;
      mClientIds = clientIds;
      mInitialised = false;
      mIsNewAccountWizard = options.isNewAccountWizard;
      mIsAccountPaymentDetailsWizard = options.isAccountPaymentDetailsWizard;
      mIsPaymentWizard = options.isPaymentWizard;
      mDefaultValuesOnPaymentMethodChange = options.defaultValuesOnPaymentMethodChange;
      mWarningMessage = "";
      if (mWarningTimer) {
        window.clearTimeout(mWarningTimer);
        mWarningTimer = null;
      }
      UpdateElement(false);

      // Other
      if (!mOptions.showCashRegister) {
        C.trCashRegister.hide();
      }

      // Get Initialisation details
      var params = {
        accountId: mAccountId,
        branchId: options.branchId,
        paymentFlowDirection: "incoming"
      };
      widget._SystemGetString("AccountPaymentDetails_Initialise", params,
        function (data) {
          if (data) {
            // Parse
            data = JSON.parse(data);
            mRecord = data;
            mPaymentMethods = data.PaymentMethodsList;
            mPaymentMethodsFiltered = mPaymentMethods;

            // Lists
            C.cboAccountEmail.ListFromCsvString(data.AccountEmailList);
            C.cboAccountPhone.ListFromCsvString(data.AccountPhoneList);
            PaymentTypeCategoryFilter(mPaymentTypeCategoryFilter);

            // Apply defaults
            if (options.applyDefaultPaymentMethod) {
              C.cboPaymentMethod.Text(data.DefaultPaymentMethodId);

              // Notify
              var e = {};
              if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_self, e);
            }
            if (options.applyDefaultCashRegister) {
              C.cboCashRegister.Text(data.DefaultCashRegisterId);
            }

            // Reference Tags
            var tags = [];
            if (mAccountId !== undefined && !mOptions.readOnly) {
              if (mOptions.paymentEntry) {
                tags = [
                  { caption: "Account ID", value: mAccountId },
                  { caption: "Name", value: mRecord.TagAccName },
                  { caption: "External ID", value: mRecord.TagExtId },
                  { caption: "Main Client ID", value: mRecord.TagMainClientId },
                  { caption: "Last Name", value: mRecord.TagLastName },
                  { caption: "Account Type ID", value: mRecord.TagATId },
                  { caption: "Bank Ref Code", value: mRecord.TagATCode },
                ];
              }
              else {
                tags = [
                  { caption: "Account ID", value: "[AccId]" },
                  { caption: "Name", value: "[AccName]" },
                  { caption: "External ID", value: "[ExtId]" },
                  { caption: "Main Client ID", value: "[ClientId]" },
                  { caption: "Last Name", value: "[LastName]" },
                  { caption: "Account Type ID", value: "[ATId]" },
                  { caption: "Bank Ref Code", value: "[ATCode]" },
                ];
              }              
            }
            C.txtReference1.TagsListDefine(tags);
            C.txtReference2.TagsListDefine(tags);
            C.txtReference3.TagsListDefine(tags);
            C.txtDescription.TagsListDefine(tags);

            // Finalise
            mInitialised = true;
            UpdateElement(true);

            // Load smart?
            if (options.defaultValuesOnPaymentMethodChange && data.DefaultPaymentMethodId) {
              if (mOptions.paymentEntry && !options.skipLoadAccountDetailsSmart) {
                LoadAccountDetailsSmart();
              }
              else {
                // Do not automatically default details when initialising the control for non-Payment Entry use, only when Payment Method changes
              }
            }
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: Failed to retrieve initialisation details: " + data);
          UpdateElement(false);
        }
      );
    }

    // -----------------------------
    // PRIVATE: Open PayTo Agreement
    // -----------------------------
    function PayToOpenAgreement() {
      // Block UI
      Block("Retrieving Agreement, please wait...");

      // Params
      var params = {
        accountId: mAccountId,
        payToId: C.cboExternalIdCombo.Text(),
      };

      widget._SystemGetString("AccountPaymentDetails_PayTo_OpenAgreement", params,
        function (data) {
          if (data) {
            // Parse
            data = JSON.parse(data);

            // Open Service Log
            if (data.SummaryHtml) {
              widget.UI.Forms.ShowHtml("PayTo Agreement - " + C.cboExternalIdCombo.Text(), data.SummaryHtml);
            }
            else if (data.ServiceLogPk) {
              widget.ExecuteApplicationShortcutUrl("app://formshow?form=ServiceLog&id=" + encodeURIComponent(data.ServiceLogPk) + "&page=Banking Interface Summary");
            }            
            
            // Unblock UI
            Unblock();
          }
        },

        function (data) {
          // Register error
          widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: Failed to Open PayTo Agreement: " + data);

          // Alert User
          if (data) widget.UI.MsgBoxAlert(data, {}, null);

          // Unblock UI
          Unblock();
        }
      );
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      C.cboPaymentMethod.Focus();
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------------
    // PUBLIC: Show Cash Register property
    // -----------------------------------
    function ShowCashRegister(value) {
      if (value === undefined) {
        // Get
        return mOptions.showCashRegister;
      }
      else {
        // Set
        mOptions.showCashRegister = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // ----------------------------------------------------------
    // PUBLIC: Selected Payment Method Has Fee read-only property
    // ----------------------------------------------------------
    function SelectedPaymentMethodHasFee() {
      if (mPaymentMethodsFiltered && C.cboPaymentMethod.ListIndex() != -1) {
        return mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].HasFee;
      }
      else {
        return false;
      }
    }

    // -------------------------------------------------------------------
    // PUBLIC: Selected Payment Method Is Direct Credit read-only property
    // -------------------------------------------------------------------
    function SelectedPaymentMethodIsDirectCredit() {
      if (mPaymentMethodsFiltered && C.cboPaymentMethod.ListIndex() != -1) {
        return mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].IsDirectCredit;
      }
      else {
        return false;
      }
    }

    // ------------------------------------------------------------------
    // PUBLIC: Selected Payment Method Is Direct Debit read-only property
    // ------------------------------------------------------------------
    function SelectedPaymentMethodIsDirectDebit() {
      if (mPaymentMethodsFiltered && C.cboPaymentMethod.ListIndex() != -1) {
        return mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].IsDirectDebit;
      }
      else {
        return false;
      }
    }

    // -------------------------
    // PUBLIC: ReadOnly property
    // -------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = value;

          UpdateElement();
        }
      }
    }

    // -------------------------------------------
    // PUBLIC: Payment Method Allow Blank property
    // -------------------------------------------
    function PaymentMethodAllowBlank(value) {
      if (value === undefined) {
        // Get
        return C.cboPaymentMethod.AllowBlank();
      }
      else {
        // Set
        C.cboPaymentMethod.AllowBlank(value);
      }
    }

    // --------------------------------
    // PUBLIC: PaymentMethodId property
    // --------------------------------
    function PaymentMethodId(value) {
      if (value === undefined) {
        // Get
        return C.cboPaymentMethod.Text();
      }
      else {
        // Set
        if (value != C.cboPaymentMethod.Text()) {
          C.cboPaymentMethod.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------------------
    // PUBLIC: Cash Register ReadOnly property
    // ---------------------------------------
    function CashRegisterReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.cashRegisterReadOnly;
      }
      else {
        // Set
        if (value != mOptions.cashRegisterReadOnly) {
          mOptions.cashRegisterReadOnly = value;

          UpdateElement();
        }
      }
    }

    // ------------------------------
    // PUBLIC: Payment Entry property
    // ------------------------------
    function PaymentEntry(value) {
      if (value === undefined) {
        // Get
        return mOptions.paymentEntry;
      }
      else {
        // Set
        if (value != mOptions.paymentEntry) {
          mOptions.paymentEntry = value;

          UpdateElement();
        }
      }
    }

    // ----------------------------------------
    // PUBLIC: Payment Method ReadOnly property
    // ----------------------------------------
    function PaymentMethodReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.paymentMethodReadOnly;
      }
      else {
        // Set
        if (value != mOptions.paymentMethodReadOnly) {
          mOptions.paymentMethodReadOnly = value;

          UpdateElement();
        }
      }
    }

    // --------------------------------
    // PUBLIC: AccountSortCode property
    // --------------------------------
    function AccountSortCode(value) {
      if (value === undefined) {
        // Get
        return C.cboAccountSortCode.Text();
      }
      else {
        // Set
        if (value != C.cboAccountSortCode.Text()) {
          C.cboAccountSortCode.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ------------------------------
    // PUBLIC: AccountNumber property
    // ------------------------------
    function AccountNumber(value) {
      if (value === undefined) {
        // Get
        return C.txtAccountNumber.Text();
      }
      else {
        // Set
        if (value != C.txtAccountNumber.Text()) {
          C.txtAccountNumber.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ----------------------------
    // PUBLIC: AccountName property
    // ----------------------------
    function AccountName(value) {
      if (value === undefined) {
        // Get
        return C.txtName.Text();
      }
      else {
        // Set
        if (value != C.txtName.Text()) {
          C.txtName.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------------------------------
    // PUBLIC: CardExpiryMonthIndex property (0 = January)
    // ---------------------------------------------------
    function CardExpiryMonthIndex(value) {
      if (value === undefined) {
        // Get
        return C.cboCardExpiryMonth.ListIndex();
      }
      else {
        // Set
        C.cboCardExpiryMonth.ListIndex(value);

        // Update Element
        UpdateElement(true);
      }
    }

    // -------------------------------
    // PUBLIC: CardExpiryYear property
    // -------------------------------
    function CardExpiryYear(value) {
      if (value === undefined) {
        // Get
        return Runtime_ParseNumber(C.cboCardExpiryYear.Text());
      }
      else {
        // Set
        C.cboCardExpiryYear.Text(Runtime_ParseNumber(value));

        // Update Element
        UpdateElement(true);
      }
    }

    // ---------------------------------
    // PUBLIC: CardSecurityCode property
    // ---------------------------------
    function CardSecurityCode(value) {
      if (value === undefined) {
        // Get
        return C.txtCardSecurityCode.Text();
      }
      else {
        // Set
        C.txtCardSecurityCode.Text(value);

        // Update Element
        UpdateElement(true);
      }
    }

    // -------------------------------
    // PUBLIC: CashRegisterId property
    // -------------------------------
    function CashRegisterId(value) {
      if (value === undefined) {
        // Get
        return C.cboCashRegister.Text();
      }
      else {
        // Set
        C.cboCashRegister.Text(value);

        // Update Element
        UpdateElement(true);
      }
    }

    // ---------------------------
    // PUBLIC: Reference1 property
    // ---------------------------
    function Reference1(value) {
      if (value === undefined) {
        // Get
        return C.txtReference1.Text();
      }
      else {
        // Set
        if (value != C.txtReference1.Text()) {
          C.txtReference1.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------
    // PUBLIC: Reference2 property
    // ---------------------------
    function Reference2(value) {
      if (value === undefined) {
        // Get
        return C.txtReference2.Text();
      }
      else {
        // Set
        if (value != C.txtReference2.Text()) {
          C.txtReference2.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------
    // PUBLIC: Reference3 property
    // ---------------------------
    function Reference3(value) {
      if (value === undefined) {
        // Get
        return C.txtReference3.Text();
      }
      else {
        // Set
        if (value != C.txtReference3.Text()) {
          C.txtReference3.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // --------------------------------------------------------------------
    // PUBLIC: Update values from a JSON formatted finBankingDetails object
    // --------------------------------------------------------------------
    function FromBankingDetailsJson(json, doNotBlankExisting) {
      // Initialise
      if (!doNotBlankExisting) doNotBlankExisting = false;

      // Parse
      if (json) {
        try {
          var o = JSON.parse(json);

          // Update fields
          // NOTE: Cash Register is set by its own property - not included in Banking Details
          if (!doNotBlankExisting || o.AccountNumber || o.AccountName) {
            C.cboPaymentMethod.Text(o.PaymentMethodId);
            C.cboAccountSortCode.Text(o.AccountSortCode);
            C.txtAccountNumber.Text(o.AccountNumber);
            C.txtName.Text(o.AccountName);
            CardExpiryMonthIndex(o.CardExpiryMonthIndex);
            if (o.CardExpiryYear && o.CardExpiryYear != -1) {
              C.cboCardExpiryYear.Text(o.CardExpiryYear);
            }
            else {
              C.cboCardExpiryYear.Text("");
            }
            C.txtCardSecurityCode.Text(o.CardSecurityCode);
          }

          C.txtReference1.Text(o.Reference1);
          C.txtReference2.Text(o.Reference2);
          C.txtReference3.Text(o.Reference3);

          C.txtDescription.Text(o.Description);

          C.cboAccountEmail.Text(o.AccountEmail);
          C.cboAccountPhone.Text(o.AccountPhone);
          C.txtExternalId.Text(o.ExternalId);
          C.cboExternalIdCombo.Text(o.ExternalId2);

          // Initialise
          if (o.AccountId) {
            // Saves having to independently call the Initialise method
            if (mAccountId != o.AccountId) {
              Initialise(o.AccountId, false);
            }
            else {
              UpdateElement(true);
            }
          }
          else {
            UpdateElement(true);
          }
        }
        catch (ex) {
          console.warn("widget.UI.AccountIncomingPaymentDetails: Error calling FromBankingDetailsJson: " + ex);
        }
      }
    }

    // ------------------------------------------
    // PUBLIC: Load smart details for the Account
    // ------------------------------------------
    function LoadAccountDetailsSmart(loadCompleteCallback, loadFailCallback) {
      // Validate
      if (mOptions.readOnly) {
        // Do nothing
        return;
      }
      else if (!mInitialised) {
        widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: LoadAccountDetailsSmart failed since the control has not been initialised.");
        if (loadFailCallback) loadFailCallback("Control has not been initialised.");
        return;
      }
      else if (!C.cboPaymentMethod.Text()) {
        widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: LoadAccountDetailsSmart failed since no Payment Method is entered.");
        if (loadFailCallback) loadFailCallback("No Payment Method is entered.");
        return;
      }

      // Initialise
      var paymentTypeCategory = "";
      var paymentMethod = null;
      if (C.cboPaymentMethod.ListIndex() != -1) {
        paymentMethod = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()];
        paymentTypeCategory = paymentMethod.PaymentTypeCategory;
      }
      else if (C.cboPaymentMethod.Text()) {
        C.cboPaymentMethod.Text("");
      }

      // Not applicable to Cash
      if (paymentTypeCategory.toUpperCase() == "CASH") {
        return;
      }

      // Block UI
      Block("Looking up payment details, please wait...");

      // Create Parameters
      var params = {
        accountId: mAccountId,
        paymentFlowDirection: "incoming",
        paymentMethodId: C.cboPaymentMethod.Text(),
        resolveReference: mOptions.resolveReference,
        paymentEntry: mOptions.paymentEntry,
      };

      // Fetch
      widget._SystemGetString("AccountPaymentDetails_LoadAccountDetailsSmart", params,
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Load Controls
          if (data.AccountId == mAccountId && data.PaymentMethodId == C.cboPaymentMethod.Text()) {
            if (data.BankingDetailsJson) {
              // Indicate to not blank out existing details if none are returned
              FromBankingDetailsJson(data.BankingDetailsJson, true);
            }
          }
          else {
            // Something's changed so do not update!
          }

          // Unblock UI
          Unblock();
        },

        function (data) {
          widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: Failed to load smart details: " + data);

          // Unblock UI
          Unblock();
        });
    }


    // -----------------------------------------------------
    // PUBLIC: Get a JSON formatted finBankingDetails object
    // -----------------------------------------------------
    function ToBankingDetailsJson() {
      var o = {};

      // NOTE: Cash Register is retrieved by its own property - not included in Banking Details
      o.PaymentMethodId = C.cboPaymentMethod.Text();
      o.AccountSortCode = C.cboAccountSortCode.Text();
      o.AccountNumber = C.txtAccountNumber.Text();
      o.AccountName = C.txtName.Text();
      o.CardExpiryMonthIndex = CardExpiryMonthIndex();
      if (C.cboCardExpiryYear.Text()) {
        o.CardExpiryYear = C.cboCardExpiryYear.Text(o.CardExpiryYear);
      }
      else {
        o.CardExpiryYear = -1;
      }
      o.CardSecurityCode = C.txtCardSecurityCode.Text();
      o.Description = C.txtDescription.Text();
      o.Reference1 = C.txtReference1.Text();
      o.Reference2 = C.txtReference2.Text();
      o.Reference3 = C.txtReference3.Text();
      o.AccountEmail = C.cboAccountEmail.Text();
      o.AccountPhone = C.cboAccountPhone.Text();
      o.ExternalId = C.txtExternalId.Text();
      o.ExternalId2 = C.cboExternalIdCombo.Text();

      return JSON.stringify(o);
    }

    // ------------------------------------------
    // PUBLIC: PaymentTypeCategoryFilter property
    // ------------------------------------------
    function PaymentTypeCategoryFilter(value) {
      if (value === undefined) {
        // Get
        return mPaymentTypeCategoryFilter;
      }
      else {
        // Set
        if (!value) value = "";

        mPaymentTypeCategoryFilter = value;

        // Filter Payment Methods list
        mPaymentMethodsFiltered = [];
        if (mPaymentMethods) {
          for (var i = 0; i < mPaymentMethods.length; i++) {
            var item = mPaymentMethods[i];
            var include = false;

            switch (mPaymentTypeCategoryFilter.toUpperCase()) {
              case "":
                // All
                include = true;
                break;

              case "DIRECTCREDIT":
                // Special, pseudo-category
                if (item.PaymentFlowDirection == "Outgoing") {
                  switch (item.PaymentTypeCategory.toUpperCase()) {
                    case "BANK":
                    case "TOKEN":
                    case "SPLIT":
                    case "ZEPTONZ":
                      include = true;
                      break;
                  }
                }
                break;

              default:
                // Named Payment Type Category
                if (item.PaymentTypeCategory == mPaymentTypeCategoryFilter) {
                  include = true;
                }
                break;
            }

            // Other Checks
            if (include) {
              if (mIsAccountPaymentDetailsWizard && item.ExcludeFromAccountPaymentDetailsWizard) include = false;
              if (mIsNewAccountWizard && item.ExcludeFromNewAccountWizard) include = false;              
              if (mIsPaymentWizard && item.ExcludeFromPaymentWizard) include = false;
            }

            // Add
            if (include) {
              mPaymentMethodsFiltered.push(item);
            }
          }
        }

        // Update Control
        C.cboPaymentMethod.RefreshFromCollection(mPaymentMethodsFiltered, "PaymentMethodId", "Description");
      }
    }

    // --------------------------------
    // PUBLIC: TransactionDate property
    // --------------------------------
    function TransactionDate(value) {
      if (value === undefined) {
        // Get
        return mTransactionDate;
      }
      else {
        // Set
        if (widget.CompareDates(value, mTransactionDate) != 0) {
          mTransactionDate = value;

          // Refresh
          UpdateElement(true);
        }
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent() {
      C.txtName.WidthResizeFromParent();
      C.txtAccountNumber.WidthResizeFromParent();
    }

    // -----------------------------------------------------------------
    // PRIVATE: Lookup Banking Details from this Account and its Clients
    // -----------------------------------------------------------------
    function BankingDetailsLookup() {
      // Modal options
      var options = {
        //closeOnEscape: true,
        height: "95%",
        width: "95%",
        maxHeight: 1024,
        maxWidth: 800,
        title: "Lookup Banking Details",
      };

      // Create Modal
      var Modal = widget.UI.Modal(options);
      var actions = [
        { groupId: "[buttons]", actionId: "Ok", caption: "OK", enabled: false },
        { groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
      ];
      Modal.Actions().Define(actions);

      Modal.OnAction(function (actionId) {
        switch (actionId) {
          case "Cancel":
            Modal.Hide(true);
            break;

          default:
            BankingDetailsLookup_Select(Modal, record_BankingDetails[grid.ActiveDataRowListIndex()]);
            break;
        }
      });

      // Define HTML Content
      var content = "";
      content += "<div class='is-dock-fill'></div>";

      // Show (content will be set in the next block)
      Modal.Show({ content: content });

      // Grids
      var record_BankingDetails = {};
      var e = $("div", Modal.ContentElement());
      var grid = Grid(e, {
        docked: true,
        showSearchBox: true,
        stickyHeader: true,

        onInitialiseRow: function (e) {
          var item = record_BankingDetails[e.row.listIndex];

          // Update cells
          e.row.AutoBind(item);
          e.row.cells.PaymentTypeId.value = "<nobr>" + SplitWordsAtCapitals(item.PaymentTypeId) + "</nobr>";

          // Styles
          e.row.cells.ClientName.small = true;
        },

        onRowDrilldown: function (e) {
          BankingDetailsLookup_Select(Modal, record_BankingDetails[grid.ActiveDataRowListIndex()]);
        },

        onAfterRowActivate: function (e) {
          Modal.Actions().SetEnabled("Ok", grid.ActiveDataRowIndex() != -1);
          Modal.Refresh();
        }
      });
      grid.AddColumnDrilldown("Drilldown", {});
      grid.AddColumnIcon("PaymentTypeIcon", { });
      grid.AddColumnCode("ClientId", { caption: "Client" });
      grid.AddColumnCode("ClientName", { caption: "Name", width: "50%" });
      grid.AddColumnHtml("PaymentTypeId", { caption: "Type", width: "8em" });
      grid.AddColumnString("Description", { caption: "Description", width: "50%" });

      // Lookup
      widget._SystemGetString("BankingDetails_LookupIncoming", { accountId: mAccountId, clientIds: mClientIds },
        function (data) {
          // Parse
          record_BankingDetails = JSON.parse(data);
          grid.VirtualDataRefresh(record_BankingDetails);
        },

        function (error) {
          widget.UI.MsgBoxAlert(error, {}, function () { Modal.Close(); });
          widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: Failed to lookup banking details: " + error);
        }
      );
    }

    function BankingDetailsLookup_Select(modal, item) {
      var newPaymentMethodId = "";
      var oldPaymentMethodId = C.cboPaymentMethod.Text();

      // Set Banking Details
      FromBankingDetailsJson(item.BankingDetailsHtmlWidgetJson);

      // Set Payment Method
      if (item.IsBankInterface && item.PaymentMethodId) {
        // Zepto
        newPaymentMethodId = item.PaymentMethodId;
      }
      else if (item.ClientId && oldPaymentMethodId && mPaymentMethodsFiltered) {
        C.cboPaymentMethod.Text(oldPaymentMethodId);
        // Client only holds Payment Type so preserve existing Payment Method Id if it is compatibile
        var paymentTypeCategory = "";
        if (C.cboPaymentMethod.ListIndex() != -1) paymentTypeCategory = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].PaymentTypeCategory;
        if (paymentTypeCategory == item.PaymentTypeCategory) {
          // Preserve
        }
        else {
          // Update (the item will contain the first compatible Payment Method)
          newPaymentMethodId = item.PaymentMethodId;
        }
      }
      else {
        newPaymentMethodId = item.PaymentMethodId;
      }

      // Set Payment Method
      // Need to ensure new Payment Method is in the list of available ones - it may have been excluded from a specific wizard (J030146)
      if (newPaymentMethodId) {
        var found = false;
        for (var i = 0; i < mPaymentMethodsFiltered.length; i++) {
          if (mPaymentMethodsFiltered[i].PaymentMethodId == newPaymentMethodId) {
            found = true;
            C.cboPaymentMethod.Text(newPaymentMethodId);
          }
        }

        // If not found, then find one with the same Category and set
        if (!found) {
          for (var i = 0; i < mPaymentMethodsFiltered.length; i++) {
            if (mPaymentMethodsFiltered[i].PaymentTypeCategory == item.PaymentTypeCategory) {
              found = true;
              C.cboPaymentMethod.Text(mPaymentMethodsFiltered[i].PaymentMethodId);
            }
          }
        }
        
        // Clear if still not found (this will trigger the error below)
        if (!found) C.cboPaymentMethod.Text("");
      }      
      
      // Update
      UpdateElement(true);

      // Hide modal
      if (C.cboPaymentMethod.Text()) {
        modal.Hide(true);
      }
      else {
        MsgBoxAlert("There are no Payment Methods available to support the selected Banking Details.", {}, null);
      }      

      // Focus
      C.cboPaymentMethod.Focus();

      // Notify
      if (oldPaymentMethodId != item.PaymentMethodId) {
        var e = {};
        if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_self, e);
      }
    }

    function txtExternalId_ButtonClick(sender, e) {
      switch (e.id) {
        case "Add":
          var list = [];
          list.push("The Client has accepted the Zepto Payments Direct Debit Request Service Agreement.");
          var message = "";
          if (widget.Options.countryCode == "AU") {
            message = "NOTE: If a Contact with the same Bank Account, Name and Email already exists the existing Contact is returned.\n\nConfirm the following to continue:";
          }
          else {
            message = "NOTE: If a Contact with the same Bank Account, Name, Email and Phone Number already exists the existing Contact is returned.\n\nConfirm the following to continue:";
          }
          MsgBoxConfirmList(message, list, { heading: "Add Zepto Contact", icon: "Logo_Zepto" }, txtExternalId_ButtonClick_Add);
          break;

        case "Verify":
          txtExternalId_ButtonClick_Verify();
          break;
      }
    }

    function txtExternalId_ButtonClick_Add() {
      Block("Creating Contact, please wait...");

      // Create Parameters
      var params = JSON.parse(ToBankingDetailsJson());
      params.AccountId = mAccountId;
      params.Email = C.cboAccountEmail.Text();
      params.Phone = C.cboAccountPhone.Text();

      widget._SystemGetString("AccountPaymentDetails_Zepto_CreateContact", params,
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Update Controls
          C.txtName.Text(data.AccountName);
          C.cboAccountEmail.Text(data.Email);
          C.cboAccountPhone.Text(data.Phone);
          C.txtExternalId.Text(data.ContactId);

          // Refresh Warnings
          UpdateElement(true);

          // Unblock
          Unblock();
        },

        function (error) {
          // Unblock
          Unblock();

          // Error
          MsgBoxAlert(error);
        }
      );
    }

    function txtExternalId_ButtonClick_Verify() {
      var url = "app://Global?type=BankingInterface.Verify";
      if (mAccountId) url += "&accountId=" + encodeURIComponent(mAccountId);
      url += "&bankingDetailsJson=" + ToBankingDetailsJson();
      widget.ExecuteApplicationShortcutUrl(url);
    }

    function cboExternalIdCombo_OnChange(sender, e) {
      if (e) e.ChangeHandled = true;
      
      // Show / Hide button
      if (mAccountId && C.cboExternalIdCombo.Text()) {
        C.trOpenAgreement.show();
      }
      else {
        C.trOpenAgreement.hide();
      }

      // Update Controls
      if (e) UpdateElement(true);
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "AccountIncomingPaymentDetails",

      //AutoReadOnly: AutoReadOnly,
      //Element: Element,
      Focus: Focus,
      Initialise: Initialise,
      ReadOnly: ReadOnly,
      Visible: Visible,

      LoadAccountDetailsSmart: LoadAccountDetailsSmart,

      FromBankingDetailsJson: FromBankingDetailsJson,
      ToBankingDetailsJson: ToBankingDetailsJson,

      PaymentEntry: PaymentEntry,
      PaymentMethodId: PaymentMethodId,
      PaymentMethodAllowBlank: PaymentMethodAllowBlank,
      PaymentMethodReadOnly: PaymentMethodReadOnly,
      PaymentTypeCategoryFilter: PaymentTypeCategoryFilter,
      AccountSortCode: AccountSortCode,
      AccountNumber: AccountNumber,
      AccountName: AccountName,
      CardExpiryMonthIndex: CardExpiryMonthIndex,
      CardExpiryYear: CardExpiryYear,
      CardSecurityCode: CardSecurityCode,
      CashRegisterId: CashRegisterId,
      CashRegisterReadOnly: CashRegisterReadOnly,
      Reference1: Reference1,
      Reference2: Reference2,
      Reference3: Reference3,

      ShowCashRegister: ShowCashRegister,

      TransactionDate: TransactionDate,

      SelectedPaymentMethodHasFee: SelectedPaymentMethodHasFee,
      SelectedPaymentMethodIsDirectCredit: SelectedPaymentMethodIsDirectCredit,
      SelectedPaymentMethodIsDirectDebit: SelectedPaymentMethodIsDirectDebit,

      WidthResizeFromParent: WidthResizeFromParent,
    };
    return _self;
  }



  // ====================================================================================
  // PUBLIC: AccountPaymentDetails object (deprecated ,use AccountIncomingPaymentDetails)
  // ====================================================================================
  function AccountPaymentDetails(e, options) {
    console.warn("Use widget.UI.AccountIncomingPaymentDetails instead of widget.UI.AccountPaymentDetails.");
    return AccountIncomingPaymentDetails(e, options);
  }



  // ============================================
  // PUBLIC: AccountOutgoingPaymentDetails object
  // ============================================
  function AccountOutgoingPaymentDetails(e, options) {

    var mAccountId;
    var mDefaultValuesOnPaymentMethodChange = false;
    var mElement;
    var mInitialised = false;
    var mIsAccountPaymentDetailsWizard = false;
    var mIsNewAccountWizard = false;
    var mIsWithdrawal = false;    
    var mOptions;
    var mPaymentTypeCategoryFilter = "";
    var mPaymentMethods;
    var mPaymentMethodsFiltered;
    var mRecord;
    var mTransactionDate = null;
    var mWarningMessage = "";
    var mWarningTimer;    

    var C = {
      trPaymentMethod: null,
      cmdExistingDetailsLookup: null,
      cboPaymentMethod: null,

      trAccountSortCode: null,
      cboAccountSortCode: null,

      trAccountNumber: null,
      txtAccountNumber: null,

      trName: null,
      txtName: null,

      trCardExpiry: null,
      cboCardExpiryMonth: null,
      cboCardExpiryYear: null,
      txtCardSecurityCode: null,

      trReference: null,
      divReferenceTagsList: null,
      txtReference1: null,
      txtReference2: null,
      txtReference3: null,

      trAccountEmail: null,
      cboAccountEmail: null,
      trExternalId: null,
      txtExternalId: null,

      trCashRegister: null,
      cboCashRegister: null,

      trWarning: null,
      divWarning: null,
    };

    // Extend options with defaults
    AccountPaymentDetailsDefaults = {
      allowBlank: false,
      readOnly: false,
      autoReadOnly: true,
      visible: true,

      paymentEntry: false, // Show fields specific to making a payment (rather than just recording banking details)
      historic: false, // Affects how list of Credit Card Expiry Years is built
      resolveReference: false, // Resolve reference tags, e.g., for Payment Entry

      showCashRegister: false,
      showExistingDetailsLookup: true, // Show a button that looks up existing Payment Details, e.g., those defined on the Account Clients

      paymentMethodVisible: true, // Ways to restrict the control, e.g., when using in a Client Portal
      paymentMethodReadOnly: false,

      cashRegisterReadOnly: false,

      hideSplitAddButton: false, // Determines if the Add Contact button for Zepto should not be displayed

      onPaymentMethodChange: null,
    };
    mOptions = $.extend({}, AccountPaymentDetailsDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.AccountOutgoingPaymentDetails: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Validate Element
    switch (mElement.prop("tagName")) {
      case "TBODY":
        break;

      default:
        console.warn("widget_ui.AccountOutgoingPaymentDetails: Element '" + id + "' must be a TBODY element.");
        return;
    }

    // Create sub-elements and controls
    //   Payment Method
    var cid = CreateGuid(true);
    C.trPaymentMethod = $("<tr style='display:none'><th><label for='" + cid + "'>Method:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trPaymentMethod);
    C.cboPaymentMethod = DBCombo($("input", C.trPaymentMethod), {
      allowBlank: mOptions.allowBlank,
      limitToList: true,
      maxLength: 10,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
        if (C.cboPaymentMethod.Text() && mDefaultValuesOnPaymentMethodChange) {
          LoadAccountDetailsSmart();
        }

        // Notify
        var e = {};
        if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_self, e);
      },
    });
    //   Lookup Existing
    C.cmdExistingDetailsLookup = $("<button tabindex='-1' class='is-button small' style='margin-left:4px' icon='Find' title='Lookup banking details from this Account and its Clients'>Lookup</button>");
    $("label.is-combobox", C.cboPaymentMethod.WrapperElement()).before(C.cmdExistingDetailsLookup);
    C.cmdExistingDetailsLookup.on("click", BankingDetailsLookup);
    ApplyIcons(C.cmdExistingDetailsLookup);
    //    Account Sort Code
    cid += "X";
    C.trAccountSortCode = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Sort Code:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountSortCode);
    C.cboAccountSortCode = DBCombo($("input", C.trAccountSortCode), {
      allowBlank: false,
      maxLength: 10,
      width: "8em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    //    Account Number/ Credit Card Number
    cid += "X";
    C.trAccountNumber = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Account No.:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountNumber);
    C.txtAccountNumber = TextBox($("input", C.trAccountNumber), {
      allowBlank: false,
      maxLength: 30,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    //    Name
    cid += "X";
    C.trName = $("<tr style='display:none'><th><label for='" + cid + "'>Name:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trName);
    C.txtName = TextBox($("input", C.trName), {
      allowBlank: true,
      maxLength: 100,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    //    Card Expiry + Card Security Code
    cid += "X";
    C.trCardExpiry = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Card Expiry:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/> <input id='" + cid + "2'/>  <input id='" + cid + "3'/></td>");
    mElement.append(C.trCardExpiry);
    C.cboCardExpiryMonth = ComboBox($($("input", C.trCardExpiry)[0]), {
      allowBlank: true,
      listCsv: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
      limitToList: false,
      maxLength: 3,
      width: "4em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.cboCardExpiryMonth.Element().blur(function () {
      // Allow month to be entered as a numeric value
      if (C.cboCardExpiryMonth.Text()) {
        var month = Runtime_ParseNumber(C.cboCardExpiryMonth.Text());
        if (month > 0) {
          // Convert to list value
          C.cboCardExpiryMonth.ListIndex(month - 1);
        }
        else {
          // Limit to list
          if (!C.cboCardExpiryMonth.ListExists(C.cboCardExpiryMonth.Text())) {
            C.cboCardExpiryMonth.Text("");
          }
        }
      }
    });
    C.cboCardExpiryYear = ComboBox($($("input", C.trCardExpiry)[1]), {
      allowBlank: true,
      limitToList: false,
      maxLength: 4,
      width: "5em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.cboCardExpiryYear.Element().blur(function () {
      // Allow 2-digit year entry
      if (C.cboCardExpiryYear.Text()) {
        var year = Runtime_ParseNumber(C.cboCardExpiryYear.Text());
        if (year < 100) year += 2000;
        if (year > 9999) year = 9999;
        C.cboCardExpiryYear.Text(year);
      }
    });
    var arrYears = [];
    var start = new Date().getFullYear(), end = start + 10;
    if (mOptions.historic) start -= 10;
    for (var i = start; i < end; i++) {
      arrYears.push(i + "");
    }
    C.cboCardExpiryYear.ListFromArray(arrYears);
    //    Card Security Code
    C.txtCardSecurityCode = TextBox($($("input", C.trCardExpiry)[2]), {
      allowBlank: false,
      maxLength: 10,
      width: "7em",
    });
    //    Reference
    cid += "X";
    C.trReference = $("<tr style='display:none'><th><label for='" + cid + "P'>Reference:</label></th><td><div id='" + cid + "TL'></div><input id='" + cid + "P'/> <input id='" + cid + "C'/> <input id='" + cid + "R'/></td>");
    mElement.append(C.trReference);
    C.divReferenceTagsList = $("div", C.trReference);
    C.txtReference1 = TextBox($($("input", C.trReference)[0]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.txtReference2 = TextBox($($("input", C.trReference)[1]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.txtReference3 = TextBox($($("input", C.trReference)[2]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    //    Zepto
    cid += "X";
    C.trAccountEmail = $("<tr style='display:none'><th><label for='" + cid + "'>Email:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountEmail);
    C.cboAccountEmail = ComboBox($("input", C.trAccountEmail), {
      allowBlank: true,
      maxLength: 255,
      width: "100%",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });
    cid += "X";
    C.trAccountPhone = $("<tr style='display:none'><th><label for='" + cid + "'>Phone:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountPhone);
    C.cboAccountPhone = ComboBox($("input", C.trAccountPhone), {
      allowBlank: true,
      maxLength: 255,
      width: "100%",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        if (C.txtExternalId.Text()) C.txtExternalId.Text("");
        UpdateElement(true);
      },
    });    
    cid += "X";
    C.trExternalId = $("<tr style='display:none'><th><label for='" + cid + "'>Contact ID:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trExternalId);
    C.txtExternalId = TextBox($("input", C.trExternalId), {
      allowBlank: true,
      maxLength: 50,

      onButtonClick: txtExternalId_ButtonClick,
      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    var buttons = [];
    buttons.push({ id: "Add", tooltipText: "Add", icon: "Add" });
    buttons.push({ id: "Verify", tooltipText: "Verify", icon: "Check" });
    C.txtExternalId.ButtonsDefine(buttons);
    //    Cash Register
    cid += "X";
    C.trCashRegister = $("<tr style='display:none'><th><label for='" + cid + "'>Cash&nbsp;Register:&nbsp;</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trCashRegister);
    C.cboCashRegister = DBCombo($("input", C.trCashRegister), {
      allowBlank: true,
      maxLength: 10,
      width: widget.UI.FIELD_WIDTH_CODE_10,
    });
    //    Warning
    cid += "X";
    C.trWarning = $("<tr style='display:none'><th colspan='2'><div class='is-info-text info' style='color:darkred; margin-bottom:0 !important; margin-top:0 !important; width:100%'></div></th>");
    mElement.append(C.trWarning);
    C.divWarning = $("div", C.trWarning);

    // Update element
    UpdateElement(false);


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement(refetchWarningMessage) {
      // Initialise
      if (mWarningTimer && (refetchWarningMessage || !C.cboPaymentMethod.Text())) {
        window.clearTimeout(mWarningTimer);
        mWarningTimer = null;
      }

      // Read-only
      //if (mOptions.readOnly) {
      //  mElement.addClass("is-readonly");
      //  mElement.attr("readonly", "readonly");
      //  mButtonElement.hide();
      //}
      //else {
      //  mElement.removeClass("is-readonly");
      //  mElement.removeAttr("readonly");
      //  mButtonElement.show();
      //  mButtonElement.css("display", "inline-block");
      //}

      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }

      // Layout and Configuration
      // NOTE: Do not arbitrarily hide controls since they lose focus!
      if (!mInitialised) C.trPaymentMethod.hide();
      if (!mWarningMessage || !C.cboPaymentMethod.Text()) C.trWarning.hide();

      if (mInitialised) {
        // Layout
        if (!mOptions.readOnly && !mOptions.paymentMethodReadOnly && mOptions.showExistingDetailsLookup && (mAccountId || mClientIds)) {
          C.cmdExistingDetailsLookup.show();
        }
        else {
          C.cmdExistingDetailsLookup.hide();
        }

        if (mOptions.paymentMethodVisible) {
          C.trPaymentMethod.show();
        }
        else {
          C.trPaymentMethod.hide();
        }
        var paymentTypeCategory = "";
        var paymentMethod = null;
        if (C.cboPaymentMethod.ListIndex() != -1) {
          paymentMethod = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()];
          paymentTypeCategory = paymentMethod.PaymentTypeCategory;
        }
        else if (C.cboPaymentMethod.Text()) {
          C.cboPaymentMethod.Text("");
        }

        // Account Sort Code
        if (mRecord && mRecord.BankSortCodeCaption) {
          if (mRecord.ShowFullAccountSortCodeList) {
            C.cboAccountSortCode.ShowDropdown(true);
            C.cboAccountSortCode.RefreshFromStandardRange("BankBranches");
          }
          else {
            C.cboAccountSortCode.ShowDropdown(false);
          }
        }

        // Card Security Code
        var CardSecurityCodeRequired = paymentMethod && paymentMethod.CscRequired;
        if (paymentMethod) C.txtCardSecurityCode.BlankTip(paymentMethod.CscDescription);

        switch (paymentTypeCategory.toUpperCase()) {
          case "":
            // Unknown
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            break;

          case "BANK":
            // Bank Account
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.cboAccountSortCode.Caption(mRecord.BankSortCodeCaption + ":");
              C.trAccountSortCode.show();
            }
            else {
              C.trAccountSortCode.hide();
            }

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.show();

            if (mRecord) C.txtReference1.BlankTip(mRecord.Reference1Caption);
            if (mRecord) C.txtReference1.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(mRecord && mRecord.Reference1Caption);

            if (mRecord) C.txtReference2.BlankTip(mRecord.Reference2Caption);
            if (mRecord) C.txtReference2.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference2.WidthResizeFromParent();
            C.txtReference2.Visible(mRecord && mRecord.Reference2Caption != null);

            if (mRecord) C.txtReference3.BlankTip(mRecord.Reference3Caption);
            if (mRecord) C.txtReference3.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference3.WidthResizeFromParent();
            C.txtReference3.Visible(mRecord && mRecord.Reference3Caption != null);

            if (mRecord.Reference1Caption && mRecord.Reference2Caption) {
              C.txtReference1.Caption("References:");
            }
            else {
              C.txtReference1.Caption("Reference:");
              C.txtReference1.BlankTip("");
            }

            C.cboAccountSortCode.AllowBlank(!paymentMethod.HasExportService);
            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);
            C.trAccountEmail.hide();
            C.trExternalId.hide();
            break;

          case "CASH":
            // Cash
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            if (mOptions.showCashRegister && paymentMethod.IsCashRegisterUsed) {
              C.trCashRegister.show();
              C.cboCashRegister.AllowBlank(!paymentMethod.IsCashRegisterRequired);
            }
            else {
              C.trCashRegister.hide();
            }
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            break;

          case "CHEQUE":
            // Cheque
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            if (mOptions.showCashRegister && paymentMethod.IsCashRegisterUsed) {
              C.trCashRegister.show();
              C.cboCashRegister.AllowBlank(!paymentMethod.IsCashRegisterRequired);
            }
            else {
              C.trCashRegister.hide();
            }
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();

            C.trName.show();
            C.txtName.Caption("Drawer:");
            C.txtName.WidthResizeFromParent();

            if (mOptions.paymentEntry) {
              C.txtName.AllowBlank(!paymentMethod.HasExportService);
            }
            else {
              C.txtName.AllowBlank(true);
            }
            C.trAccountEmail.hide();
            C.trExternalId.hide();
            break;

          case "CREDITCARD":
            // Credit Card
            C.trAccountSortCode.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Card No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Card Name:");
            C.txtName.WidthResizeFromParent();

            C.trCardExpiry.show();
            C.txtCardSecurityCode.Visible(CardSecurityCodeRequired);

            C.trReference.show();
            C.txtReference1.BlankTip("");
            C.txtReference1.Caption("Reference:");
            C.txtReference1.MaxLength(50);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(true);
            C.txtReference2.Visible(false);
            C.txtReference3.Visible(false);

            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(true);
            C.cboCardExpiryMonth.AllowBlank(!paymentMethod.HasExportService);
            C.cboCardExpiryYear.AllowBlank(!paymentMethod.HasExportService);
            break;

          case "MONOOVA":
            // Monoova
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountPhone.hide();
            C.trAccountEmail.hide();
            C.trExternalId.hide();

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.cboAccountSortCode.AllowBlank(false);
              C.cboAccountSortCode.Caption(mRecord.BankSortCodeCaption + ":");
              C.trAccountSortCode.show();
            }
            else {
              C.trAccountSortCode.hide();
            }

            C.trAccountNumber.show();
            C.txtAccountNumber.AllowBlank(false);
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);
            C.txtName.Caption("Name:")
            C.txtName.WidthResizeFromParent();

            C.trReference.show();
            C.txtReference2.Visible(false);
            C.txtReference3.Visible(false);

            C.txtReference1.Visible(true);
            C.txtReference1.AllowBlank(true);
            C.txtReference1.BlankTip("");
            C.txtReference1.MaxLength(18);
            C.txtReference1.WidthResizeFromParent();
            break;

          case "POSCARD":
            // POS Card
            C.trAccountSortCode.hide();
            C.trReference.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Card No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Card Name:");
            C.txtName.WidthResizeFromParent();

            C.trCardExpiry.show();
            C.txtCardSecurityCode.Visible(CardSecurityCodeRequired);

            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);
            C.cboCardExpiryMonth.AllowBlank(!paymentMethod.HasExportService);
            C.cboCardExpiryYear.AllowBlank(!paymentMethod.HasExportService);
            break;

          case "SPLIT":
            // Zepto (formally Split Payments)
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountPhone.hide();

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.cboAccountSortCode.Caption(mRecord.BankSortCodeCaption + ":");
              C.trAccountSortCode.show();
            }
            else {
              C.trAccountSortCode.hide();
            }

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.hide();

            C.cboAccountSortCode.AllowBlank(false);
            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);

            C.trAccountEmail.show();
            C.trExternalId.show();
            C.txtExternalId.WidthResizeFromParent();
            break;

          case "ZEPTONZ":
            // Zepto NZ
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountSortCode.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.hide();

            C.cboAccountSortCode.AllowBlank(false);
            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(!paymentMethod.IsBankAccountOtherPartyNameRequired);

            C.trAccountEmail.show();
            C.trAccountPhone.show();
            C.trExternalId.show();
            C.txtExternalId.WidthResizeFromParent();
            break;

          case "TOKEN":
            // Token (like Bank Account but without the same validation)
            C.trAccountSortCode.hide();
            C.trCardExpiry.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Token:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.show();

            if (mRecord) C.txtReference1.BlankTip(mRecord.Reference1Caption);
            if (mRecord) C.txtReference1.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(mRecord && mRecord.Reference1Caption);

            if (mRecord) C.txtReference2.BlankTip(mRecord.Reference2Caption);
            if (mRecord) C.txtReference2.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference2.WidthResizeFromParent();
            C.txtReference2.Visible(mRecord && mRecord.Reference2Caption != null);

            if (mRecord) C.txtReference3.BlankTip(mRecord.Reference3Caption);
            if (mRecord) C.txtReference3.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference3.WidthResizeFromParent();
            C.txtReference3.Visible(mRecord && mRecord.Reference3Caption != null);

            if (mRecord.Reference1Caption && mRecord.Reference2Caption) {
              C.txtReference1.Caption("References:");
            }
            else {
              C.txtReference1.Caption("Reference:");
              C.txtReference1.BlankTip("");
            }

            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(true);
            break;

          default:
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            C.trCashRegister.hide();
            C.trAccountEmail.hide();
            C.trAccountPhone.hide();
            C.trExternalId.hide();
            window.alert("Unhandled Payment Type Category '" + paymentTypeCategory + "'.");
        }

        // Other
        if (mRecord) {
        }

        // Cash Register
        if (mOptions.showCashRegister && paymentMethod && paymentMethod.IsCashRegisterUsed) {
          if (!C.cboCashRegister.__Refreshed) {
            C.cboCashRegister.RefreshFromStandardRange("CashRegisters");
            C.cboCashRegister.__Refreshed = true;
          }
        }

        // Read-Only
        C.cboPaymentMethod.ReadOnly(mOptions.readOnly || mOptions.paymentMethodReadOnly);
        C.cboAccountSortCode.ReadOnly(mOptions.readOnly);
        C.txtAccountNumber.ReadOnly(mOptions.readOnly);
        C.txtName.ReadOnly(mOptions.readOnly);
        C.cboCardExpiryMonth.ReadOnly(mOptions.readOnly);
        C.cboCardExpiryYear.ReadOnly(mOptions.readOnly);
        C.txtCardSecurityCode.ReadOnly(mOptions.readOnly);
        C.txtReference1.ReadOnly(mOptions.readOnly);
        C.txtReference2.ReadOnly(mOptions.readOnly);
        C.txtReference3.ReadOnly(mOptions.readOnly);
        C.cboCashRegister.ReadOnly(mOptions.readOnly || mOptions.cashRegisterReadOnly);

        // Buttons
        C.txtExternalId.Buttons().ButtonVisible("Add", !mOptions.hideSplitAddButton);
        C.txtExternalId.Buttons().ButtonVisible("Verify", C.txtExternalId.Text() != "");

        // Warning
        // NOTE: Also updates Account Number and Sort Code formats if necessary
        if (refetchWarningMessage && mRecord && C.cboPaymentMethod.Text()) {
          mWarningTimer = window.setTimeout(function () {
            window.clearTimeout(mWarningTimer);
            mWarningTimer = null;

            // Fetch warning
            var params = { bankingDetailsJson: ToBankingDetailsJson() };
            if (mAccountId) params.AccountId = mAccountId;
            if (mTransactionDate) params.TransactionDate = mTransactionDate;

            widget._SystemGetString("AccountPaymentDetails_GetValidationDetails", params,
              function (data) {
                if (data) {
                  // Parse
                  data = JSON.parse(data);
                  mWarningMessage = data.Message;

                  // Format Account Number and Sort Code
                  if (!mOptions.readOnly) {
                    if (C.txtAccountNumber.Text() && C.txtAccountNumber.Text() == data.AccountNumberOriginal && data.AccountNumberFormatted) {
                      C.txtAccountNumber.Text(data.AccountNumberFormatted);
                    }

                    if (C.cboAccountSortCode.Text() && C.cboAccountSortCode.Text() == data.AccountSortCodeOriginal && data.AccountSortCodeFormatted) {
                      C.cboAccountSortCode.Text(data.AccountSortCodeFormatted);
                    }
                  }
                }
                else {
                  // Returned nothing!
                  mWarningMessage = "";
                }

                C.divWarning.html(HtmlEncode(mWarningMessage));
                if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
                if (data.Warning) C.divWarning.css("color", "darkred"); else C.divWarning.css("color", "green");
              },

              function (data) {
                mWarningMessage = data;
                widget.RegisterError("widget_ui.AccountOutgoingPaymentDetails: Failed to retrieve validation details: " + data);

                C.divWarning.html(HtmlEncode(mWarningMessage));
                if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
              }
            );
          }, 750);
        }
        else {
          if (C.cboPaymentMethod.Text()) {
            C.divWarning.html(HtmlEncode(mWarningMessage));
            if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
          }
          else {
            C.trWarning.hide();
          }
        }
      }
      else {
        if (mWarningMessage) {
          C.divWarning.html(HtmlEncode(mWarningMessage));
        }
        else {
          C.divWarning.css("color", "darkred");
          C.divWarning.text("Initialising, please wait...");
        }
        C.trWarning.show();
      }
    }

    // ------------------
    // PUBLIC: Initialise
    // ------------------
    function Initialise(accountId, options, clientIds) {
      // Extend options with defaults
      var InitialiseDefaults = {
        applyDefaultPaymentMethod: false,
        applyDefaultCashRegister: false,

        branchId: "",

        defaultValuesOnPaymentMethodChange: false,
        skipLoadAccountDetailsSmart: false,

        isAccountPaymentDetailsWizard: false,
        isNewAccountWizard: false,
        isWithdrawal: false,
      };
      options = $.extend({}, InitialiseDefaults, options);

      // Initialise
      mAccountId = accountId;
      mClientIds = clientIds;
      mInitialised = false;
      mIsAccountPaymentDetailsWizard = options.isAccountPaymentDetailsWizard;
      mIsNewAccountWizard = options.isNewAccountWizard;
      mIsWithdrawal = options.isWithdrawal;
      mDefaultValuesOnPaymentMethodChange = options.defaultValuesOnPaymentMethodChange;
      mWarningMessage = "";
      if (mWarningTimer) {
        window.clearTimeout(mWarningTimer);
        mWarningTimer = null;
      }
      UpdateElement(false);

      // Other
      if (mOptions.showCashRegister) {
        C.cboCashRegister.RefreshFromStandardRange("CashRegisters");
      }
      else {
        C.cboCashRegister.VisibleRow(false);
      }

      // Get Initialisation details
      var params = {
        accountId: mAccountId,
        branchId: options.branchId,
        paymentFlowDirection: "outgoing"
      };
      widget._SystemGetString("AccountPaymentDetails_Initialise", params,
        function (data) {
          if (data) {
            // Parse
            data = JSON.parse(data);
            mRecord = data;
            mPaymentMethods = data.PaymentMethodsList;
            mPaymentMethodsFiltered = mPaymentMethods;
            
            // Lists
            C.cboAccountEmail.ListFromCsvString(data.AccountEmailList);
            C.cboAccountPhone.ListFromCsvString(data.AccountPhoneList);
            PaymentTypeCategoryFilter(mPaymentTypeCategoryFilter);
            
            // Apply defaults
            if (options.applyDefaultPaymentMethod) {
              C.cboPaymentMethod.Text(data.DefaultPaymentMethodId);

              // Notify
              var e = {};
              if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_self, e);
            }
            if (options.applyDefaultCashRegister) {
              C.cboCashRegister.Text(data.DefaultCashRegisterId);
            }

            // Reference Tags
            var tags = [];
            if (mAccountId !== undefined && !mOptions.readOnly) {
              if (mOptions.paymentEntry) {
                tags = [
                  { caption: "Account ID", value: mAccountId },
                  { caption: "Name", value: mRecord.TagAccName },
                  { caption: "External ID", value: mRecord.TagExtId },
                  { caption: "Main Client ID", value: mRecord.TagMainClientId },
                  { caption: "Last Name", value: mRecord.TagLastName },
                  { caption: "Account Type ID", value: mRecord.TagATId },
                  { caption: "Bank Ref Code", value: mRecord.TagATCode },
                ];
              }
              else {
                tags = [
                  { caption: "Account ID", value: "[AccId]" },
                  { caption: "Name", value: "[AccName]" },
                  { caption: "External ID", value: "[ExtId]" },
                  { caption: "Main Client ID", value: "[ClientId]" },
                  { caption: "Last Name", value: "[LastName]" },
                  { caption: "Account Type ID", value: "[ATId]" },
                  { caption: "Bank Ref Code", value: "[ATCode]" },
                ];
              }
            }
            C.txtReference1.TagsListDefine(tags);
            C.txtReference2.TagsListDefine(tags);
            C.txtReference3.TagsListDefine(tags);

            // Finalise
            mInitialised = true;
            UpdateElement(true);

            // Load smart?
            if (options.defaultValuesOnPaymentMethodChange && data.DefaultPaymentMethodId) {
              if (mOptions.paymentEntry && !options.skipLoadAccountDetailsSmart) {
                LoadAccountDetailsSmart();
              }
              else {
                // Do not automatically default details when initialising the control for non-Payment Entry use, only when Payment Method changes
              }
            }
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.AccountOutgoingPaymentDetails: Failed to retrieve initialisation details: " + data);
          UpdateElement(false);
        }
      );
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      C.cboPaymentMethod.Focus();
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------------
    // PUBLIC: Show Cash Register property
    // -----------------------------------
    function ShowCashRegister(value) {
      if (value === undefined) {
        // Get
        return mOptions.showCashRegister;
      }
      else {
        // Set
        mOptions.showCashRegister = value;

        // Refresh
        UpdateElement(false);
      }
    }


    // -----------------------------------
    // PUBLIC: Show Cheque Number property
    // -----------------------------------
    function ShowChequeNumber(value) {
      if (value === undefined) {
        // Get
        return false; //mOptions.showCashRegister;
      }
      else {
        // Set
        //mOptions.showCashRegister = value;
        //TODO:

        // Refresh
        UpdateElement(false);
      }
    }

    // ----------------------------------------------------------
    // PUBLIC: Selected Payment Method Has Fee read-only property
    // ----------------------------------------------------------
    function SelectedPaymentMethodHasFee() {
      if (mPaymentMethodsFiltered && C.cboPaymentMethod.ListIndex() != -1) {
        return mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].HasFee;
      }
      else {
        return false;
      }
    }

    // -------------------------------------------------------------------
    // PUBLIC: Selected Payment Method Is Direct Credit read-only property
    // -------------------------------------------------------------------
    function SelectedPaymentMethodIsDirectCredit() {
      if (mPaymentMethodsFiltered && C.cboPaymentMethod.ListIndex() != -1) {
        return mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].IsDirectCredit;
      }
      else {
        return false;
      }
    }

    // ------------------------------------------------------------------
    // PUBLIC: Selected Payment Method Is Direct Debit read-only property
    // ------------------------------------------------------------------
    function SelectedPaymentMethodIsDirectDebit() {
      if (mPaymentMethodsFiltered && C.cboPaymentMethod.ListIndex() != -1) {
        return mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].IsDirectDebit;
      }
      else {
        return false;
      }
    }

    // -------------------------
    // PUBLIC: ReadOnly property
    // -------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = value;

          UpdateElement();
        }
      }
    }

    // ------------------------------
    // PUBLIC: Payment Entry property
    // ------------------------------
    function PaymentEntry(value) {
      if (value === undefined) {
        // Get
        return mOptions.paymentEntry;
      }
      else {
        // Set
        if (value != mOptions.paymentEntry) {
          mOptions.paymentEntry = value;

          UpdateElement();
        }
      }
    }

    // -------------------------------------------
    // PUBLIC: Payment Method Allow Blank property
    // -------------------------------------------
    function PaymentMethodAllowBlank(value) {
      if (value === undefined) {
        // Get
        return C.cboPaymentMethod.AllowBlank();
      }
      else {
        // Set
        C.cboPaymentMethod.AllowBlank(value);
      }
    }

    // --------------------------------
    // PUBLIC: PaymentMethodId property
    // --------------------------------
    function PaymentMethodId(value) {
      if (value === undefined) {
        // Get
        return C.cboPaymentMethod.Text();
      }
      else {
        // Set
        if (value != C.cboPaymentMethod.Text()) {
          C.cboPaymentMethod.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------------------
    // PUBLIC: Cash Register ReadOnly property
    // ---------------------------------------
    function CashRegisterReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.cashRegisterReadOnly;
      }
      else {
        // Set
        if (value != mOptions.cashRegisterReadOnly) {
          mOptions.cashRegisterReadOnly = value;

          UpdateElement();
        }
      }
    }

    // ----------------------------------------
    // PUBLIC: Payment Method ReadOnly property
    // ----------------------------------------
    function PaymentMethodReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.paymentMethodReadOnly;
      }
      else {
        // Set
        if (value != mOptions.paymentMethodReadOnly) {
          mOptions.paymentMethodReadOnly = value;

          UpdateElement();
        }
      }
    }

    // --------------------------------
    // PUBLIC: AccountSortCode property
    // --------------------------------
    function AccountSortCode(value) {
      if (value === undefined) {
        // Get
        return C.cboAccountSortCode.Text();
      }
      else {
        // Set
        if (value != C.cboAccountSortCode.Text()) {
          C.cboAccountSortCode.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ------------------------------
    // PUBLIC: AccountNumber property
    // ------------------------------
    function AccountNumber(value) {
      if (value === undefined) {
        // Get
        return C.txtAccountNumber.Text();
      }
      else {
        // Set
        if (value != C.txtAccountNumber.Text()) {
          C.txtAccountNumber.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ----------------------------
    // PUBLIC: AccountName property
    // ----------------------------
    function AccountName(value) {
      if (value === undefined) {
        // Get
        return C.txtName.Text();
      }
      else {
        // Set
        if (value != C.txtName.Text()) {
          C.txtName.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------------------------------
    // PUBLIC: CardExpiryMonthIndex property (0 = January)
    // ---------------------------------------------------
    function CardExpiryMonthIndex(value) {
      if (value === undefined) {
        // Get
        return C.cboCardExpiryMonth.ListIndex();
      }
      else {
        // Set
        C.cboCardExpiryMonth.ListIndex(value);

        // Update Element
        UpdateElement(true);
      }
    }

    // -------------------------------
    // PUBLIC: CardExpiryYear property
    // -------------------------------
    function CardExpiryYear(value) {
      if (value === undefined) {
        // Get
        return Runtime_ParseNumber(C.cboCardExpiryYear.Text());
      }
      else {
        // Set
        C.cboCardExpiryYear.Text(Runtime_ParseNumber(value));

        // Update Element
        UpdateElement(true);
      }
    }

    // ---------------------------------
    // PUBLIC: CardSecurityCode property
    // ---------------------------------
    function CardSecurityCode(value) {
      if (value === undefined) {
        // Get
        return C.txtCardSecurityCode.Text();
      }
      else {
        // Set
        C.txtCardSecurityCode.Text(value);

        // Update Element
        UpdateElement(true);
      }
    }

    // -------------------------------
    // PUBLIC: CashRegisterId property
    // -------------------------------
    function CashRegisterId(value) {
      if (value === undefined) {
        // Get
        return C.cboCashRegister.Text();
      }
      else {
        // Set
        C.cboCashRegister.Text(value);

        // Update Element
        UpdateElement(true);
      }
    }

    // ---------------------------
    // PUBLIC: Reference1 property
    // ---------------------------
    function Reference1(value) {
      if (value === undefined) {
        // Get
        return C.txtReference1.Text();
      }
      else {
        // Set
        if (value != C.txtReference1.Text()) {
          C.txtReference1.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------
    // PUBLIC: Reference2 property
    // ---------------------------
    function Reference2(value) {
      if (value === undefined) {
        // Get
        return C.txtReference2.Text();
      }
      else {
        // Set
        if (value != C.txtReference2.Text()) {
          C.txtReference2.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------
    // PUBLIC: Reference3 property
    // ---------------------------
    function Reference3(value) {
      if (value === undefined) {
        // Get
        return C.txtReference3.Text();
      }
      else {
        // Set
        if (value != C.txtReference3.Text()) {
          C.txtReference3.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // --------------------------------------------------------------------
    // PUBLIC: Update values from a JSON formatted finBankingDetails object
    // --------------------------------------------------------------------
    function FromBankingDetailsJson(json, doNotBlankExisting) {
      // Parse
      if (json) {
        try {
          var o = JSON.parse(json);

          // Update fields
          // NOTE: Cash Register is set by its own property - not included in Banking Details
          if (!doNotBlankExisting || o.AccountNumber || o.AccountName) {
            C.cboPaymentMethod.Text(o.PaymentMethodId);
            C.cboAccountSortCode.Text(o.AccountSortCode);
            C.txtAccountNumber.Text(o.AccountNumber);
            C.txtName.Text(o.AccountName);
            CardExpiryMonthIndex(o.CardExpiryMonthIndex);
            if (o.CardExpiryYear && o.CardExpiryYear != -1) {
              C.cboCardExpiryYear.Text(o.CardExpiryYear);
            }
            else {
              C.cboCardExpiryYear.Text("");
            }
            C.txtCardSecurityCode.Text(o.CardSecurityCode);
          }

          C.txtReference1.Text(o.Reference1);
          C.txtReference2.Text(o.Reference2);
          C.txtReference3.Text(o.Reference3);

          C.cboAccountEmail.Text(o.AccountEmail);
          C.cboAccountPhone.Text(o.AccountPhone);
          C.txtExternalId.Text(o.ExternalId);

          // Initialise
          if (o.AccountId) {
            // Saves having to independently call the Initialise method
            if (mAccountId != o.AccountId) {
              Initialise(o.AccountId, false);
            }
            else {
              UpdateElement(true);
            }
          }
          else {
            UpdateElement(true);
          }
        }
        catch (ex) {
          console.warn("widget.UI.AccountOutgoingPaymentDetails: Error calling FromBankingDetailsJson: " + ex);
        }
      }
    }

    // ------------------------------------------
    // PUBLIC: Load smart details for the Account
    // ------------------------------------------
    function LoadAccountDetailsSmart(loadCompleteCallback, loadFailCallback) {
      // Validate
      if (mOptions.readOnly) {
        // Do nothing
        return;
      }
      else if (!mInitialised) {
        widget.RegisterError("widget_ui.AccountOutgoingPaymentDetails: LoadAccountDetailsSmart failed since the control has not been initialised.");
        if (loadFailCallback) loadFailCallback("Control has not been initialised.");
        return;
      }
      else if (!C.cboPaymentMethod.Text()) {
        widget.RegisterError("widget_ui.AccountOutgoingPaymentDetails: LoadAccountDetailsSmart failed since no Payment Method is entered.");
        if (loadFailCallback) loadFailCallback("No Payment Method is entered.");
        return;
      }

      // Initialise
      var paymentTypeCategory = "";
      var paymentMethod = null;
      if (C.cboPaymentMethod.ListIndex() != -1) {
        paymentMethod = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()];
        paymentTypeCategory = paymentMethod.PaymentTypeCategory;
      }
      else if (C.cboPaymentMethod.Text()) {
        C.cboPaymentMethod.Text("");
      }

      // Not applicable to Cash
      if (paymentTypeCategory.toUpperCase() == "CASH") {
        return;
      }

      // Block UI
      Block("Looking up payment details, please wait...");

      // Create Parameters
      var params = {
        accountId: mAccountId,
        paymentFlowDirection: "outgoing",
        paymentMethodId: C.cboPaymentMethod.Text(),
        resolveReference: mOptions.resolveReference,
        paymentEntry: mOptions.paymentEntry,
      };

      // Fetch
      widget._SystemGetString("AccountPaymentDetails_LoadAccountDetailsSmart", params,
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Load Controls
          if (data.AccountId == mAccountId && data.PaymentMethodId == C.cboPaymentMethod.Text()) {
            // Indicate to not blank out existing details if none are returned
            FromBankingDetailsJson(data.BankingDetailsJson, true);
          }
          else {
            // Something's changed so do not update!
          }

          // Unblock UI
          Unblock();
        },

        function (data) {
          widget.RegisterError("widget_ui.AccountOutgoingPaymentDetails: Failed to load smart details: " + data);

          // Unblock UI
          Unblock();
        });
    }

    // -----------------------------------------------------
    // PUBLIC: Get a JSON formatted finBankingDetails object
    // -----------------------------------------------------
    function ToBankingDetailsJson() {
      var o = {};

      // NOTE: Cash Register is retrieved by its own property - not included in Banking Details
      o.PaymentMethodId = C.cboPaymentMethod.Text();
      o.AccountSortCode = C.cboAccountSortCode.Text();
      o.AccountNumber = C.txtAccountNumber.Text();
      o.AccountName = C.txtName.Text();
      o.CardExpiryMonthIndex = CardExpiryMonthIndex();
      if (C.cboCardExpiryYear.Text()) {
        o.CardExpiryYear = C.cboCardExpiryYear.Text(o.CardExpiryYear);
      }
      else {
        o.CardExpiryYear = -1;
      }
      o.CardSecurityCode = C.txtCardSecurityCode.Text();
      o.Reference1 = C.txtReference1.Text();
      o.Reference2 = C.txtReference2.Text();
      o.Reference3 = C.txtReference3.Text();
      o.AccountEmail = C.cboAccountEmail.Text();
      o.AccountPhone = C.cboAccountPhone.Text();
      o.ExternalId = C.txtExternalId.Text();

      return JSON.stringify(o);
    }

    // ------------------------------------------
    // PUBLIC: PaymentTypeCategoryFilter property
    // ------------------------------------------
    function PaymentTypeCategoryFilter(value) {
      if (value === undefined) {
        // Get
        return mPaymentTypeCategoryFilter;
      }
      else {
        // Set
        if (!value) value = "";

        var changed = mPaymentTypeCategoryFilter != value;
        mPaymentTypeCategoryFilter = value;

        // Filter Payment Methods list
        mPaymentMethodsFiltered = [];
        if (mPaymentMethods) {          
          for (var i = 0; i < mPaymentMethods.length; i++) {
            var item = mPaymentMethods[i];
            var include = false;

            switch (mPaymentTypeCategoryFilter.toUpperCase()) {
              case "":
                // All
                include = true;
                break;

              case "DIRECTCREDIT":
                // Special, pseudo-category
                if (item.PaymentFlowDirection == "Outgoing") {
                  switch (item.PaymentTypeCategory.toUpperCase()) {
                    case "BANK":
                    case "TOKEN":
                    case "SPLIT":
                    case "ZEPTONZ":
                      include = true;
                      break;
                  }
                }
                break;

              default:
                // Named Payment Type Category
                if (item.PaymentTypeCategory == mPaymentTypeCategoryFilter) {
                  include = true;
                }
                break;
            }

            // Other Checks
            if (include) {
              if (mIsAccountPaymentDetailsWizard && item.ExcludeFromAccountPaymentDetailsWizard) include = false;
              if (mIsNewAccountWizard && item.ExcludeFromNewAccountWizard) include = false;
              if (mIsWithdrawal && item.ExcludeFromWithdrawalWizard) include = false;              
            }

            // Add
            if (include) {
              mPaymentMethodsFiltered.push(item);
            }
          }
        }

        // Update Control
        C.cboPaymentMethod.RefreshFromCollection(mPaymentMethodsFiltered, "PaymentMethodId", "Description");

        // Ensure warning message is regenerated since we may have filtered for Cheques but currently be showing a Direct Credit Payment Method (J027336)
        UpdateElement(changed && !mOptions.ReadOnly);
      }
    }

    // --------------------------------
    // PUBLIC: TransactionDate property
    // --------------------------------
    function TransactionDate(value) {
      if (value === undefined) {
        // Get
        return mTransactionDate;
      }
      else {
        // Set
        if (widget.CompareDates(value, mTransactionDate) != 0) {
          mTransactionDate = value;

          // Refresh
          UpdateElement(true);
        }
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent() {
      C.txtName.WidthResizeFromParent();
      C.txtAccountNumber.WidthResizeFromParent();
    }

    // -----------------------------------------------------------------
    // PRIVATE: Lookup Banking Details from this Account and its Clients
    // -----------------------------------------------------------------
    function BankingDetailsLookup() {
      // Modal options
      var options = {
        //closeOnEscape: true,
        height: "95%",
        width: "95%",
        maxHeight: 1024,
        maxWidth: 800,
        title: "Lookup Banking Details", 
      };

      // Create Modal
      var Modal = widget.UI.Modal(options);
      var actions = [
        { groupId: "[buttons]", actionId: "Ok", caption: "OK", enabled: false },
        { groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
      ];
      Modal.Actions().Define(actions);

      Modal.OnAction(function (actionId) {
        switch (actionId) {
          case "Cancel":
            Modal.Hide(true);
            break;

          default:
            BankingDetailsLookup_Select(Modal, record_BankingDetails[grid.ActiveDataRowListIndex()]);
            break;
        }
      });

      // Define HTML Content
      var content = "";
      content += "<div class='is-dock-fill'></div>";

      // Show (content will be set in the next block)
      Modal.Show({ content: content });

      // Grids
      var record_BankingDetails = {};
      var e = $("div", Modal.ContentElement());
      var grid = Grid(e, {
        docked: true,
        showSearchBox: true,
        stickyHeader: true,

        onInitialiseRow: function (e) {
          var item = record_BankingDetails[e.row.listIndex];

          // Update cells
          e.row.AutoBind(item);
          e.row.cells.PaymentTypeId.value = "<nobr>" + SplitWordsAtCapitals(item.PaymentTypeId) + "</nobr>";

          // Styles
          e.row.cells.ClientName.small = true;
        },

        onRowDrilldown: function (e) {
          BankingDetailsLookup_Select(Modal, record_BankingDetails[grid.ActiveDataRowListIndex()]);
        },

        onAfterRowActivate: function (e) {
          Modal.Actions().SetEnabled("Ok", grid.ActiveDataRowIndex() != -1);
          Modal.Refresh();
        }
      });
      grid.AddColumnDrilldown("Drilldown", {});
      grid.AddColumnIcon("PaymentTypeIcon", {});
      grid.AddColumnCode("ClientId", { caption: "Client" });
      grid.AddColumnCode("ClientName", { caption: "Name", width: "50%" });
      grid.AddColumnHtml("PaymentTypeId", { caption: "Type", width: "8em" });
      grid.AddColumnString("Description", { caption: "Description", width: "50%" });

      // Lookup
      widget._SystemGetString("BankingDetails_LookupOutgoing", { accountId: mAccountId, clientIds: mClientIds },
        function (data) {
          // Parse
          record_BankingDetails = JSON.parse(data);
          grid.VirtualDataRefresh(record_BankingDetails);
        },

        function (error) {
          widget.UI.MsgBoxAlert(error, {}, function () { Modal.Close(); });
          widget.RegisterError("widget_ui.AccountOutgoingPaymentDetails: Failed to lookup banking details: " + error);
        }
      );
    }

    function BankingDetailsLookup_Select(modal, item) {
      var newPaymentMethodId = "";
      var oldPaymentMethodId = C.cboPaymentMethod.Text();

      // Set Banking Details
      FromBankingDetailsJson(item.BankingDetailsHtmlWidgetJson);

      // Set Payment Method
      if (item.IsBankInterface && item.PaymentMethodId) {
        // Zepto
        newPaymentMethodId = item.PaymentMethodId;
      }
      else if (item.ClientId && oldPaymentMethodId && mPaymentMethodsFiltered) {
        C.cboPaymentMethod.Text(oldPaymentMethodId);
        // Client only holds Payment Type so preserve existing Payment Method Id if it is compatibile
        var paymentTypeCategory = "";
        if (C.cboPaymentMethod.ListIndex() != -1) paymentTypeCategory = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()].PaymentTypeCategory;
        if (paymentTypeCategory == item.PaymentTypeCategory) {
          // Preserve
        }
        else {
          // Update (the item will contain the first compatible Payment Method)
          newPaymentMethodId = item.PaymentMethodId;
        }
      }
      else {
        newPaymentMethodId = item.PaymentMethodId;
      }

      // Set Payment Method
      // Need to ensure new Payment Method is in the list of available ones - it may have been excluded from a specific wizard (J030146)
      if (newPaymentMethodId) {
        var found = false;
        for (var i = 0; i < mPaymentMethodsFiltered.length; i++) {
          if (mPaymentMethodsFiltered[i].PaymentMethodId == newPaymentMethodId) {
            found = true;
            C.cboPaymentMethod.Text(newPaymentMethodId);
          }
        }

        // If not found, then find one with the same Category and set
        if (!found) {
          for (var i = 0; i < mPaymentMethodsFiltered.length; i++) {
            if (mPaymentMethodsFiltered[i].PaymentTypeCategory == item.PaymentTypeCategory) {
              found = true;
              C.cboPaymentMethod.Text(mPaymentMethodsFiltered[i].PaymentMethodId);
            }
          }
        }

        // Clear if still not found (this will trigger the error below)
        if (!found) C.cboPaymentMethod.Text("");
      }

      // Update
      UpdateElement(true);

      // Hide modal
      if (C.cboPaymentMethod.Text()) {
        modal.Hide(true);
      }
      else {
        MsgBoxAlert("There are no Payment Methods available to support the selected Banking Details.", {}, null);
      }

      // Focus
      C.cboPaymentMethod.Focus();

      // Notify
      if (oldPaymentMethodId != item.PaymentMethodId) {
        var e = {};
        if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_self, e);
      }
    }

    function txtExternalId_ButtonClick(sender, e) {
      switch (e.id) {
        case "Add":
          var message = "";          
          if (widget.Options.countryCode == "AU") {
            message = "Add new Zepto Contact?\n\nNOTE: If a Contact with the same Bank Account, Name and Email already exists the existing Contact is returned.";
          }
          else {
            message = "Add new Zepto Contact?\n\nNOTE: If a Contact with the same Bank Account, Name, Email and Phone Number already exists the existing Contact is returned.";
          }
          MsgBoxConfirm(message, { heading: "Add Zepto Contact", icon: "Logo_Zepto" }, txtExternalId_ButtonClick_Add);
          break;

        case "Verify":
          txtExternalId_ButtonClick_Verify();
          break;
      }
    }

    function txtExternalId_ButtonClick_Add() {
      Block("Creating Contact, please wait...");

      // Create Parameters
      var params = JSON.parse(ToBankingDetailsJson());
      params.AccountId = mAccountId;
      params.Email = C.cboAccountEmail.Text();
      params.Phone = C.cboAccountPhone.Text();

      widget._SystemGetString("AccountPaymentDetails_Zepto_CreateContact", params,
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Update Controls
          C.txtName.Text(data.AccountName);
          C.cboAccountEmail.Text(data.Email);
          C.cboAccountPhone.Text(data.Phone);
          C.txtExternalId.Text(data.ContactId);

          // Refresh Warnings
          UpdateElement(true);

          // Unblock
          Unblock();
        },

        function (error) {
          // Unblock
          Unblock();

          // Error
          MsgBoxAlert(error);
        }
      );
    }

    function txtExternalId_ButtonClick_Verify() {
      var url = "app://Global?type=BankingInterface.Verify";
      if (mAccountId) url += "&accountId=" + encodeURIComponent(mAccountId);
      url += "&bankingDetailsJson=" + ToBankingDetailsJson();
      widget.ExecuteApplicationShortcutUrl(url);
    }



    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "AccountOutgoingPaymentDetails",

      //AutoReadOnly: AutoReadOnly,
      //Element: Element,
      Focus: Focus,
      Initialise: Initialise,
      ReadOnly: ReadOnly,
      Visible: Visible,

      LoadAccountDetailsSmart: LoadAccountDetailsSmart,

      FromBankingDetailsJson: FromBankingDetailsJson,
      ToBankingDetailsJson: ToBankingDetailsJson,

      PaymentEntry: PaymentEntry,
      PaymentTypeCategoryFilter: PaymentTypeCategoryFilter,
      PaymentMethodId: PaymentMethodId,
      PaymentMethodReadOnly: PaymentMethodReadOnly,
      PaymentMethodAllowBlank: PaymentMethodAllowBlank,
      AccountSortCode: AccountSortCode,
      AccountNumber: AccountNumber,
      AccountName: AccountName,
      CardExpiryMonthIndex: CardExpiryMonthIndex,
      CardExpiryYear: CardExpiryYear,
      CardSecurityCode: CardSecurityCode,
      CashRegisterReadOnly: CashRegisterReadOnly,
      CashRegisterId: CashRegisterId,
      Reference1: Reference1,
      Reference2: Reference2,
      Reference3: Reference3,

      ShowCashRegister: ShowCashRegister,
      ShowChequeNumber: ShowChequeNumber,

      TransactionDate: TransactionDate,

      SelectedPaymentMethodHasFee: SelectedPaymentMethodHasFee,
      SelectedPaymentMethodIsDirectCredit: SelectedPaymentMethodIsDirectCredit,
      SelectedPaymentMethodIsDirectDebit: SelectedPaymentMethodIsDirectDebit,

      WidthResizeFromParent: WidthResizeFromParent,
    };

    // Associate this control to HTML input element (for container validation)
    mElement.prop("is-control", _self);

    return _self;
  }



  // =============================
  // PUBLIC: AddressDetails object
  // =============================
  function AddressDetails(e, options) {

    // Constants
    var DEFAULT_COUNTRY_INFO = { Country: "", DeliveryTypes: "", States: "", SupportsPostcode: true, SupportsState: true, SupportsSuburb: true, TerminologyPostcode: "Postcode", TerminologyState: "State", PostalValidationAvailable: false };

    var mElement;
    var mOptions;
    var mRecord;
    var mRecordCountryInfo;
    var mTimerAddressChanged;
    var mValueData;
    var mWarningMessage = "";

    var mShowInstructionsReadOnly = false;
    var mShowDeliveryTypeReadOnly = false;
    var mShowPropertyNameReadOnly = false;
    var mShowCityReadOnly = false;
    var mShowCountryReadOnly = false;
    var mShowPostalIdReadOnly = false;

    var mInstructionsOrigValue = "";
    var mDeliveryTypeOrigValue = "";
    var mPropertyNameOrigValue = "";
    var mCityOrigValue = "";
    var mCountryOrigValue = "";
    var mPostalIdOrigValue = "";

    var C = {
      trInstructions: null,
      txtInstructions: null,

      trDeliveryType: null,
      cboDeliveryType: null,

      trPropertyName: null,
      txtPropertyName: null,

      trStreetAddress: null,
      txtStreetAddress: null,

      trBoxNumber: null,
      txtBoxNumber: null,

      trSuburb: null,
      txtSuburb: null,

      trCity: null,
      txtCity: null,

      trState: null,
      cboState: null,

      trPostcode: null,
      txtPostcode: null,

      trCountry: null,
      cboCountry: null,

      trPostalId: null,
      txtPostalId: null,
      cmdCheckPostalId: null,

      trWarning: null,
      divWarning: null,

      pulPromptUpdateList_Address: null,
    };

    // Extend options with defaults
    AddressDetailsDefaults = {
      allowBlank: true,
      readOnly: false,
      autoReadOnly: true,
      visible: true,

      captionSuffix: ":",

      showCity: true,
      showCountry: true,
      showDeliveryType: false,
      showInstructions: false,
      showPostalId: false,
      showPropertyName: false,
      excludeUnspecifiedDeliveryTypes: false,

      advancedCity: false,      // Indicates whether to add an 'advanced' class to the table row
      advancedPostalId: false,

      useAutoComplete: true,
      autoValidateAddress: false,  // Requires Full Addressing add-on

      onCountryInfoAvailable: null,
      onDeliveryTypeChange: null,
    };
    mOptions = $.extend({}, AddressDetailsDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.AddressDetails: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Validate Element
    switch (mElement.prop("tagName")) {
      case "TBODY":
        break;

      default:
        console.warn("widget_ui.AddressDetails: Element '" + id + "' must be a TBODY element.");
        return;
    }

    // Create sub-elements and controls
    var cid = CreateGuid(true);
    //    Instructions
    C.trInstructions = $("<tr style='display:none'><th><label for='" + cid + "'>Instructions" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trInstructions);
    C.txtInstructions = TextBox($("input", C.trInstructions), {
      maxLength: 255,
      multiLine: true,
      rows: 2,
    });
      
    //    Delivery Type
    cid += "X";
    C.trDeliveryType = $("<tr style='display:none'><th><label for='" + cid + "'>Delivery Type" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trDeliveryType);
    C.cboDeliveryType = ComboBox($("input", C.trDeliveryType), {
      blankTip: "Unspecified",
      limitToList: true,
      maxLength: 20,

      onChange: cboDeliveryType_Change,
    });
    //   Property Name
    cid += "X";
    C.trPropertyName = $("<tr style='display:none'><th><label for='" + cid + "'>Property&nbsp;Name" + mOptions.captionSuffix + "&nbsp;</label></th><td><input id='" + cid + "' autocomplete='off' /></td>");
    mElement.append(C.trPropertyName);
    C.txtPropertyName = TextBox($("input", C.trPropertyName), {
      maxLength: 50,

      onChange: Address_Changed,
    });
    //   Street Address
    cid += "X";
    C.trStreetAddress = $("<tr><th><label for='" + cid + "'>Street" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "' autocomplete='off' /></td>");
    mElement.append(C.trStreetAddress);
    C.txtStreetAddress = TextBox($("input", C.trStreetAddress), {
      maxLength: 130,

      onChange: Address_Changed,
    });
    //   Box Number
    cid += "X";
    C.trBoxNumber = $("<tr style='display:none'><th><label for='" + cid + "'>Box Number" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "' autocomplete='off' /></td>");
    mElement.append(C.trBoxNumber);
    C.txtBoxNumber = TextBox($("input", C.trBoxNumber), {
      maxLength: 10,
    });
    //    Suburb
    cid += "X";
    C.trSuburb = $("<tr><th><label for='" + cid + "'>Suburb" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trSuburb);
    C.txtSuburb = TextBox($("input", C.trSuburb), {
      maxLength: 50,

      onChange: Address_Changed,
    });
    //    City
    cid += "X";
    C.trCity = $("<tr style='display:none'><th><label for='" + cid + "'>City" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trCity);
    C.txtCity = TextBox($("input", C.trCity), {
      maxLength: 50,

      onChange: Address_Changed,
    });
    //    State
    cid += "X";
    C.trState = $("<tr><th><label for='" + cid + "'>State" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trState);
    C.cboState = ComboBox($("input", C.trState), {
      maxLength: 50,

      onChange: Address_Changed,
    });
    //    Postcode
    cid += "X";
    C.trPostcode = $("<tr><th><label for='" + cid + "'>Postcode" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trPostcode);
    C.txtPostcode = TextBox($("input", C.trPostcode), {
      maxLength: 10,

      onChange: Address_Changed,
    });
    //    Country
    cid += "X";
    C.trCountry = $("<tr style='display:none'><th><label for='" + cid + "'>Country" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trCountry);
    C.cboCountry = ComboBox($("input", C.trCountry), {
      maxLength: 50,

      onChange: cboCountry_Change,
    });
    //    PostalId
    cid += "X";
    C.trPostalId = $("<tr style='display:none'><th><label for='" + cid + "'>Postal Id" + mOptions.captionSuffix + "</label></th><td><input id='" + cid + "'/><button class='is-button small'>Check</button></td>");
    mElement.append(C.trPostalId);
    C.txtPostalId = TextBox($("input", C.trPostalId), {
      maxLength: 20
    });
    C.cmdCheckPostalId = $("button.is-button.small", C.trPostalId); // Reference classes so we don't accidentally pickup the TextBox control's internal buttons!
    C.cmdCheckPostalId.click(cmdCheckPostalId_Click);
    //    Warning
    cid += "X";
    C.trWarning = $("<tr style='display:none'><th colspan='2'><div class='is-info-text info' style='color:darkred; margin-bottom:0 !important; margin-top:0 !important; width:100%'></div></th>");
    mElement.append(C.trWarning);
    C.divWarning = $("div", C.trWarning);

    C.pulPromptUpdateList_Address = widget.UI.PromptUpdateList({
      onAccept: pulPromptUpdateList_Address_Accept
    });

    // Initialise Addressing
    if (mOptions.useAutoComplete) {
      widget.UI.InitialiseAddressAutoComplete({
        streetAddress: C.txtStreetAddress,
        suburb: C.txtSuburb,
        city: C.txtCity,
        state: C.cboState,
        postcode: C.txtPostcode,
        country: C.cboCountry,

        onAfterAddressAutoComplete: function () {
          // Ensure states list and other country info is updated
          if (!mOptions.readOnly) cboCountry_Change();
        }
      });
    }

    // Update element
    UpdateElement();

    // Initialise
    Initialise();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }

      // Layout and Configuration
      // NOTE: Do not arbitrarily hide controls since they lose focus!
      if (mWarningMessage) {
        C.divWarning.html(HtmlEncode(mWarningMessage));
        C.trWarning.show();
      }
      else {
        C.trWarning.hide();
      }
      
      // Set flags
      // If configured to not show a field, but that field contains data, it will be displayed as read only
      mShowInstructionsReadOnly = (!mOptions.showInstructions && mInstructionsOrigValue.length != 0);
      mShowDeliveryTypeReadOnly = (!mOptions.showDeliveryType && (mDeliveryTypeOrigValue.length != 0 && mDeliveryTypeOrigValue.toUpperCase() != "UNSPECIFIED"));
      mShowPropertyNameReadOnly = (!mOptions.showPropertyName && mPropertyNameOrigValue.length != 0);
      mShowCityReadOnly = (!mOptions.showCity && mCityOrigValue.length != 0);
      mShowCountryReadOnly = (!mOptions.showCountry && mCountryOrigValue.length != 0);
      mShowPostalIdReadOnly = (!mOptions.showPostalId && mPostalIdOrigValue.length != 0);

      // Row Visibility
      C.txtInstructions.VisibleRow(mOptions.showInstructions || mShowInstructionsReadOnly);
      C.cboDeliveryType.VisibleRow(mOptions.showDeliveryType || mShowDeliveryTypeReadOnly);
      C.txtPropertyName.VisibleRow(mOptions.showPropertyName || mShowPropertyNameReadOnly);
      C.txtCity.VisibleRow(mOptions.showCity || mShowCityReadOnly);
      C.cboCountry.VisibleRow(mOptions.showCountry || mShowCountryReadOnly);

      // Determine Delivery Type
      var deliveryType = (C.cboDeliveryType.Text() || C.cboDeliveryType.BlankTip()).toUpperCase();

      // Show Postal Id?
      if (mRecordCountryInfo) {
        C.txtPostalId.VisibleRow((mOptions.showPostalId && mRecordCountryInfo.PostalValidationAvailable) || mShowPostalIdReadOnly);
      }
      else {
        C.txtPostalId.VisibleRow(mOptions.showPostalId || mShowPostalIdReadOnly);
      }
      if (deliveryType == "UNSPECIFIED") C.txtPostalId.VisibleRow(false);

      // Read-Only
      C.txtInstructions.ReadOnly(mOptions.readOnly || mShowInstructionsReadOnly);
      C.cboDeliveryType.ReadOnly(mOptions.readOnly || mShowDeliveryTypeReadOnly);
      C.txtPropertyName.ReadOnly(mOptions.readOnly || mShowPropertyNameReadOnly);
      C.txtStreetAddress.ReadOnly(mOptions.readOnly);
      C.txtSuburb.ReadOnly(mOptions.readOnly);
      C.txtCity.ReadOnly(mOptions.readOnly || mShowCityReadOnly);
      C.cboState.ReadOnly(mOptions.readOnly);
      C.txtPostcode.ReadOnly(mOptions.readOnly);
      C.cboCountry.ReadOnly(mOptions.readOnly || mShowCountryReadOnly);
      C.txtPostalId.ReadOnly(mOptions.readOnly || mShowPostalIdReadOnly);

      // Other
      C.txtStreetAddress.AllowBlank(mOptions.allowBlank);

      // Advanced
      if (mOptions.advancedCity) C.trCity.addClass("advanced"); else C.trCity.removeClass("advanced");
      if (mOptions.advancedPostalId) C.trPostalId.addClass("advanced"); else C.trPostalId.removeClass("advanced");

      // Country Info
      if (!mRecordCountryInfo) mRecordCountryInfo = DEFAULT_COUNTRY_INFO;
      // States List
      var country = C.cboCountry.Text() || C.cboCountry.BlankTip();
      if (country == mRecordCountryInfo.Country) {
        C.cboState.ListFromCsvString(mRecordCountryInfo.States);
        C.cboState.AllowDropdown(mRecordCountryInfo.States != "");
      }
      // Terminology
      C.txtSuburb.Caption(mRecordCountryInfo.TerminologySuburb + mOptions.captionSuffix);
      C.txtCity.Caption(mRecordCountryInfo.TerminologyCity + mOptions.captionSuffix);
      C.cboState.Caption(mRecordCountryInfo.TerminologyState + mOptions.captionSuffix);
      C.txtPostcode.Caption(mRecordCountryInfo.TerminologyPostcode + mOptions.captionSuffix);
      C.txtSuburb.VisibleRow(mRecordCountryInfo.SupportsSuburb);
      C.cboState.VisibleRow(mRecordCountryInfo.SupportsState);
      C.txtPostcode.VisibleRow(mRecordCountryInfo.SupportsPostcode);
      // OtherIsDeliveryTypeBagOrBox
      if (mRecordCountryInfo.PostalValidationAvailable && !mOptions.readOnly) {
        C.cmdCheckPostalId.show();
      }
      else {
        C.cmdCheckPostalId.hide();
      }

      // Delivery Type-based tweaks
      if (IsDeliveryTypeBagOrBox()) {
        // Box or Bag
        C.txtStreetAddress.VisibleRow(false);
        C.txtBoxNumber.VisibleRow(true);
        C.txtPropertyName.VisibleRow(false);
        C.txtSuburb.VisibleRow(true);
        //C.cboState.VisibleRow(false);

        if (deliveryType.indexOf("BAG") != -1) {
          C.txtBoxNumber.Caption("Bag Number" + mOptions.captionSuffix);
        }
        else {
          C.txtBoxNumber.Caption("Box Number" + mOptions.captionSuffix);
        }
        C.txtSuburb.Caption("Location" + mOptions.captionSuffix);
      }
      else {
        // Other
        C.txtStreetAddress.VisibleRow(true);
        C.txtBoxNumber.VisibleRow(false);
        C.txtStreetAddress.Caption("Street" + mOptions.captionSuffix);
        if (mRecordCountryInfo) {
          C.txtSuburb.Caption(mRecordCountryInfo.TerminologySuburb + mOptions.captionSuffix);
        }
        else {
          C.txtSuburb.Caption("Suburb" + mOptions.captionSuffix);
        }
      }
    }

    // -------------------
    // PRIVATE: Initialise
    // -------------------
    function Initialise() {
      // Initialise
      mWarningMessage = "";

      // Get Initialisation details
      widget._SystemGetString("AddressDetails_Initialise", {},
        function (data) {
          if (data) {
            // Parse
            data = JSON.parse(data);
            mRecord = data;

            // Other
            // NOTE: Must be set before calling cboCountry_Change
            C.cboCountry.BlankTip(mRecord.DefaultCountry);

            // Lists
            C.cboCountry.ListFromCsvString(mRecord.CountriesList);

            // Limit to List
            C.cboCountry.LimitToList(mRecord.LimitCountriesToList);

            // Update Controls
            cboCountry_Change();
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.AddressDetails: Failed to retrieve initialisation details: " + data);
          UpdateElement(false);
        }
      );
    }

    // ----------
    // cboCountry
    // ----------
    function cboCountry_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update States list
      GetCountryInfo(C.cboCountry.Text() || C.cboCountry.BlankTip());

      // Address Changed
      Address_Changed();
    }

    // ----------------
    // cmdCheckPostalId
    // ----------------
    function cmdCheckPostalId_Click() {
      ValidateAddress(true, true);
    }

    // ---------------------------
    // pulPromptUpdateList_Address
    // ---------------------------
    function pulPromptUpdateList_Address_Accept(sender, e) {
      // Update
      for (var i = 0; i < e.ids.length; i++) {
        switch (e.ids[i]) {
          case "DeliveryType":
            C.cboDeliveryType.Text(mValueData.DeliveryTypeText);
            break;

          case "PostalId":
            C.txtPostalId.Text(mValueData.PostalId);
            break;

          case "Address":
            C.txtPropertyName.Text(mValueData.PropertyName);
            C.txtStreetAddress.Text(mValueData.StreetAddress);
            if (mValueData.StreetAddress) {
              // Strip out box/ bag number
              var boxNumber = "";
              for (var i = 0; i < mValueData.StreetAddress.length; i++) {
                var s = mValueData.StreetAddress.substr(i, 1);
                if ("0123456789".indexOf(s) != -1) boxNumber += s;
              }
              C.txtBoxNumber.Text(boxNumber);
            }
            C.txtSuburb.Text(mValueData.Suburb);
            C.txtCity.Text(mValueData.City);
            C.cboState.Text(mValueData.State);
            C.txtPostcode.Text(mValueData.Postcode);
            C.cboCountry.Text(mValueData.Country);
            break;
        }
      }

      // Update (e.g., to show Postal Id)
      UpdateElement();
    }

    // -------------------------
    // PRIVATE: Validate Address
    // -------------------------
    function ValidateAddress(userInvoked, validatePostalId) {
      // Initialise
      mWarningMessage = "";
      UpdateElement();
      C.pulPromptUpdateList_Address.Hide();

      // Create Parameters
      var params = { AddressJson: ToAddressDetailsJson(), ValidatePostalId: validatePostalId };

      // Validate we have enough information
      if (C.txtPostalId.Text()) {
        // Ok
      }
      else if (IsDeliveryTypeBagOrBox()) {
        if (!C.txtBoxNumber.Text()) {
          if (userInvoked) {
            widget.UI.MsgBoxAlert("You must enter either a Postal Id or Box/ Bag number.", { heading: "Check Address" }, function () { C.txtPostalId.Focus(); });
          }
          return;
        }
      }
      else {
        if (!C.txtStreetAddress.Text()) {
          if (userInvoked) {
            widget.UI.MsgBoxAlert("You must enter either a Postal Id or Street Address.", { heading: "Check Address" }, function () { C.txtPostalId.Focus(); });
          }
          return;
        }
      }

      // Ensure Postal Id is showing
      //C.txtPostalId.VisibleRow(true);

      // Validate Postal Id (or lookup Postal Id)
      widget._SystemGetString("AddressDetails_ValidateAddress", params,
        function (data) {
          // Initialise
          mTimerAddressChanged = null;

          // Prompt
          Address_Changed_PromptUpdate(data, validatePostalId, userInvoked);
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.AddressDetails: Failed to validate Postal Id: " + data);
          UpdateElement(false);
        }
      );
    }

    function Address_Changed_PromptUpdate(data, validatingPostalId, userInvoked) {
      if (data) {
        var addressJson = JSON.parse(data).UpdatedAddressJson;
        mValueData = JSON.parse(addressJson);

        // Anything to do?
        if (!mValueData.StreetAddress) return;

        // Include fields
        var showInstructions = (mOptions.showInstructions || mShowInstructionsReadOnly);
        var showDeliveryType = (mOptions.showDeliveryType || mShowDeliveryTypeReadOnly);
        var showPropertyName = (mOptions.showPropertyName || mShowPropertyNameReadOnly);
        var showCity = (mOptions.showCity || mShowCityReadOnly);
        var showCountry = (mOptions.showCountry || mShowCountryReadOnly);

        // Build update list
        var list = [];
        if (showInstructions && mValueData.Instructions && mValueData.Instructions != C.txtInstructions.Text()) {
          list.push({ id: "Instructions", caption: "Instructions", value: mValueData.Instructions });
        }
        if (showDeliveryType && mValueData.DeliveryTypeText && mValueData.DeliveryTypeText != C.cboDeliveryType.Text()) {
          list.push({ id: "DeliveryType", caption: "Delivery Type", value: mValueData.DeliveryTypeText });
        }
        if (mValueData.PostalId != C.txtPostalId.Text()) {
          list.push({ id: "PostalId", caption: "Postal Id", value: mValueData.PostalId });
        }

        var currentAddress = "";
        if (showPropertyName && C.txtPropertyName.Text()) currentAddress += C.txtPropertyName.Text() + "\n";
        if (C.txtStreetAddress.Text()) currentAddress += C.txtStreetAddress.Text() + "\n";
        if (C.txtSuburb.Text()) currentAddress += C.txtSuburb.Text() + "\n";
        if (showCity && C.txtCity.Text()) currentAddress += C.txtCity.Text() + "\n";
        if (C.cboState.Text()) currentAddress += C.cboState.Text() + "\n";
        if (C.txtPostcode.Text()) currentAddress += C.txtPostcode.Text() + "\n";
        if (showCountry && C.cboCountry.Text()) currentAddress += C.cboCountry.Text() + "\n";

        var newAddress = "";
        if (mOptions.showPropertyName && mValueData.PropertyName) newAddress += mValueData.PropertyName + "\n";
        if (mValueData.StreetAddress) newAddress += mValueData.StreetAddress + "\n";
        if (mValueData.Suburb) newAddress += mValueData.Suburb + "\n";
        if (mOptions.showCity && mValueData.City) newAddress += mValueData.City + "\n";
        if (mValueData.State) newAddress += mValueData.State + "\n";
        if (mValueData.Postcode) newAddress += mValueData.Postcode + "\n";
        if (mOptions.showCountry && mValueData.Country) newAddress += mValueData.Country + "\n";

        if (newAddress && currentAddress != newAddress) {
          list.push({ id: "Address", caption: "Address", value: newAddress });
        }

        // Show
        if (list.length == 0) {
          C.pulPromptUpdateList_Address.Hide();

          if (userInvoked) {
            if (mValueData.PostalId) {
              widget.UI.MsgBoxInfo("Postal Id matches the Address.", { heading: "Check Address" });
            }
            else {
              widget.UI.MsgBoxAlert("No Postal Id was found for this Address.", { heading: "Check Address" });
            }
          }
        }
        else {
          if (IsDeliveryTypeBagOrBox()) {
            C.pulPromptUpdateList_Address.Show(C.txtBoxNumber, list);
          }
          else {
            C.pulPromptUpdateList_Address.Show(C.txtStreetAddress, list);
          }
        }
      }
    }

    // ---------------
    // cboDeliveryType
    // ---------------
    function cboDeliveryType_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update
      UpdateElement();

      // Notify
      if (mOptions.onDeliveryTypeChange) {
        mOptions.onDeliveryTypeChange(_self, {});
      }

      // Address Changed
      Address_Changed();
    }

    // ---------------
    // Address Changed
    // ---------------
    function Address_Changed(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Ignore?
      if (mOptions.readOnly || !mOptions.autoValidateAddress || !mRecordCountryInfo || !mRecordCountryInfo.PostalValidationAvailable) {
        C.pulPromptUpdateList_Address.Hide();
        return;
      }

      // Delay slightly to account for address auto-complete
      if (mTimerAddressChanged) window.clearTimeout(mTimerAddressChanged);
      mTimerAddressChanged = window.setTimeout(Address_Changed_Start, 500);
    }

    function Address_Changed_Start() {
      ValidateAddress(false, false);
    }

    // --------------------------------
    // PRIVATE: Get Country Information
    // --------------------------------
    function GetCountryInfo(country) {
      var cacheKey = "__CountryInfo_" + country;
      var mWarningMessage = "";

      // From Cache?
      if (!country) {
        mRecordCountryInfo = DEFAULT_COUNTRY_INFO;
      }
      else if (mInformationListCache[cacheKey]) {
        mRecordCountryInfo = mInformationListCache[cacheKey];
      }
      else {
        mRecordCountryInfo = null;
      }

      // Get Country information
      if (mRecordCountryInfo) {
        GetCountryInfo_Done();
      }
      else {
        widget._SystemGetString("AddressDetails_GetCountryInfo", { country: country },
          function (data) {
            if (data) {
              // Parse
              if (data) {
                data = JSON.parse(data);
                mRecordCountryInfo = data;

                // Cache
                mInformationListCache[cacheKey] = mRecordCountryInfo;

                // Finalise
                GetCountryInfo_Done();
              }
            }
          },

          function (data) {
            mWarningMessage = data;
            widget.RegisterError("widget_ui.AddressDetails: Failed to retrieve country information: " + data);
            UpdateElement();
          }
        );
      }
    }

    function GetCountryInfo_Done() {
      UpdateElement();

      // Update Lists
      var arrDeliveryTypes = ArrayFromCsvString(mRecordCountryInfo.DeliveryTypes);
      if (mOptions.excludeUnspecifiedDeliveryTypes) {
        for (var i = arrDeliveryTypes.length - 1; i > 0; i--) {
          if (arrDeliveryTypes[i].toUpperCase().startsWith("UNSPECIFIED")) arrDeliveryTypes.splice(i, 1);
        }
      }
      C.cboDeliveryType.ListFromArray(arrDeliveryTypes);

      // Notify
      if (mOptions.onCountryInfoAvailable) {
        mOptions.onCountryInfoAvailable(_self, { countryInfo: mRecordCountryInfo });
      }
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      if (mOptions.readOnly || !C.txtStreetAddress.Text()) {
        // Safe to focus, Google auto-complete will not drop down for read-only or blank controls
        C.txtStreetAddress.Focus();
      }
      else {
        if (mOptions.showPropertyName) {
          C.txtPropertyName.Focus();
        }
        else if (mOptions.showCity) {
          C.txtCity.Focus();
        }
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // --------------------------
    // PUBLIC: Show City property
    // --------------------------
    function ShowCity(value) {
      if (value === undefined) {
        // Get
        return mOptions.showCity;
      }
      else {
        // Update Original value (if city is going to be 'hidden', but there is a value in the textbox)
        if (mOptions.showCity && !value) {
          mCityOrigValue = C.txtCity.Text();
        }

        // Set
        mOptions.showCity = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------
    // PUBLIC: Show Country property
    // -----------------------------
    function ShowCountry(value) {
      if (value === undefined) {
        // Get
        return mOptions.showCountry;
      }
      else {
        // Update Original value (if country is going to be 'hidden', but there is a value in the textbox)
        if (mOptions.showCountry && !value) {
          mCountryOrigValue = C.cboCountry.Text();
        }

        // Set
        mOptions.showCountry = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // ----------------------------------
    // PUBLIC: Show Instructions property
    // ----------------------------------
    function ShowInstructions(value) {
      if (value === undefined) {
        // Get
        return mOptions.showInstructions;
      }
      else {
        // Update Original value (if instructions are going to be 'hidden', but there is a value in the textbox)
        if (mOptions.showInstructions && !value) {
          mInstructionsOrigValue = C.txtInstructions.Text();
        }

        // Set
        mOptions.showInstructions = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------------
    // PUBLIC: Show Delivery Type property
    // -----------------------------------
    function ShowDeliveryType(value) {
      if (value === undefined) {
        // Get
        return mOptions.showDeliveryType;
      }
      else {
        // Update Original value (if delivery type is going to be 'hidden', but there is a value in the textbox)
        if (mOptions.showDeliveryType && !value) {
          mDeliveryTypeOrigValue = C.cboDeliveryType.Text();
        }

        // Set
        mOptions.showDeliveryType = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -------------------------------
    // PUBLIC: Show Postal Id property
    // -------------------------------
    function ShowPostalId(value) {
      if (value === undefined) {
        // Get
        return mOptions.showPostalId;
      }
      else {
        // Update Original value (if postal id is going to be 'hidden', but there is a value in the textbox)
        if (mOptions.showPostalId && !value) {
          mPostalIdOrigValue = C.txtPostalId.Text();
        }

        // Set
        mOptions.showPostalId = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------------
    // PUBLIC: Show Property Name property
    // -----------------------------------
    function ShowPropertyName(value) {
      if (value === undefined) {
        // Get
        return mOptions.showPropertyName;
      }
      else {
        // Update Original value (if property name is going to be 'hidden', but there is a value in the textbox)
        if (mOptions.showPropertyName && !value) {
          mPropertyNameOrigValue = C.txtPropertyName.Text();
        }

        // Set
        mOptions.showPropertyName = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------
    // PUBLIC: Auto-Validate Address
    // -----------------------------
    function AutoValidateAddress(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoValidateAddress;
      }
      else {
        // Set
        mOptions.autoValidateAddress = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // --------------------------------------
    // PUBLIC: City Row, 'advanced' CSS class
    // --------------------------------------
    function AdvancedCity(value) {
      if (value === undefined) {
        // Get
        return mOptions.advancedCity;
      }
      else {
        // Set
        mOptions.advancedCity = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -------------------------------------------
    // PUBLIC: Postal Id Row, 'advanced' CSS class
    // -------------------------------------------
    function AdvancedPostalId(value) {
      if (value === undefined) {
        // Get
        return mOptions.advancedPostalId;
      }
      else {
        // Set
        mOptions.advancedPostalId = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -------------------------
    // PUBLIC: ReadOnly property
    // -------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = value;

          UpdateElement();
        }
      }
    }

    // -------------------------------------------------------------------
    // PUBLIC: Update values from a JSON formatted ISAddressDetails object
    // -------------------------------------------------------------------
    function FromAddressDetailsJson(json) {
      // Initialise
      C.pulPromptUpdateList_Address.Hide();

      // Parse
      try {
        var o = JSON.parse(json);

        // Store original values
        // If any values are displayed as read only because the HTML Widget does not usually allow these values to be seen, it is possible that the User can force the field to show and therefore update information. This prevents that.
        mInstructionsOrigValue = o.Instructions;
        mDeliveryTypeOrigValue = o.DeliveryTypeText;
        mPropertyNameOrigValue = o.PropertyName;
        mCityOrigValue = o.City;
        mCountryOrigValue = o.Country;
        mPostalIdOrigValue = o.PostalId;

        // Update fields
        C.txtInstructions.Text(o.Instructions);
        C.cboDeliveryType.Text(o.DeliveryTypeText);
        C.txtPropertyName.Text(o.PropertyName);
        C.txtStreetAddress.Text(o.StreetAddress);
        // Strip out box/ bag number
        var boxNumber = "";
        for (var i = 0; i < o.StreetAddress.length; i++) {
          var s = o.StreetAddress.substr(i, 1);
          if ("0123456789".indexOf(s) != -1) boxNumber += s;
        }
        C.txtBoxNumber.Text(boxNumber);
        C.txtSuburb.Text(o.Suburb);
        C.txtCity.Text(o.City);
        C.cboState.Text(o.State);
        C.txtPostcode.Text(o.Postcode);
        C.cboCountry.Text(o.Country);
        C.txtPostalId.Text(o.PostalId);

        UpdateElement();
        cboCountry_Change();
      }
      catch (ex) {
        console.warn("widget.UI.AddressDetails: Error calling FromAddressDetailsJson: " + ex);
      }
    }

    // ----------------------------------------------------
    // PUBLIC: Get a JSON formatted ISAddressDetails object
    // ----------------------------------------------------
    function ToAddressDetailsJson() {
      var o = {};

      // Instructions
      if (mOptions.showInstructions) {
        o.Instructions = C.txtInstructions.Text();
      }
      else if (mShowInstructionsReadOnly) {
        o.Instructions = mInstructionsOrigValue;
      }

      // Delivery Type
      if (mOptions.showDeliveryType) {
        o.DeliveryTypeText = C.cboDeliveryType.Text();
      }
      else if (mShowDeliveryTypeReadOnly) {
        o.DeliveryTypeText = mDeliveryTypeOrigValue;
      }

      // Property Name
      if (mOptions.showPropertyName) {
        o.PropertyName = C.txtPropertyName.Text();
      }
      else if (mShowPropertyNameReadOnly) {
        o.PropertyName = mPropertyNameOrigValue;
      }

      if (IsDeliveryTypeBagOrBox()) {
        o.StreetAddress = C.cboDeliveryType.Text() + " " + C.txtBoxNumber.Text();
      }
      else {
        o.StreetAddress = C.txtStreetAddress.Text();
      }
      o.Suburb = C.txtSuburb.Text();

      // City
      if (mOptions.showCity) {
        o.City = C.txtCity.Text();
      }
      else if (mShowCityReadOnly) {
        o.City = mCityOrigValue;
      }

      o.State = C.cboState.Text();
      o.Postcode = C.txtPostcode.Text();

      // Country
      if (mOptions.showCountry) {
        o.Country = C.cboCountry.Text();
      }
      else if (mShowCountryReadOnly) {
        o.Country = mCountryOrigValue;
      }

      // Postal Id
      if (mOptions.showPostalId) {
        o.PostalId = C.txtPostalId.Text();
      }
      else if (mShowPostalIdReadOnly) {
        o.PostalId = mPostalIdOrigValue;
      }

      return JSON.stringify(o);
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent() {
      C.txtInstructions.WidthResizeFromParent();
      C.cboDeliveryType.WidthResizeFromParent();
      C.txtPropertyName.WidthResizeFromParent();
      C.txtStreetAddress.WidthResizeFromParent();
      C.txtSuburb.WidthResizeFromParent();
      C.txtCity.WidthResizeFromParent();
      C.cboState.WidthResizeFromParent();
      C.txtPostcode.WidthResizeFromParent();
      C.cboCountry.WidthResizeFromParent();
      C.txtPostalId.WidthResizeFromParent();
    }

    // -----------------------------------------------------
    // PUBLIC: Does the Delivery Type contain 'Bag' or 'Box'
    // -----------------------------------------------------
    function IsDeliveryTypeBagOrBox() {
      var s = C.cboDeliveryType.Text().toUpperCase();
      if (s.indexOf("BAG") != -1 || s.indexOf("BOX") != -1) {
        return true;
      }
      else {
        return false;
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "AddressDetails",

      //AutoReadOnly: AutoReadOnly,
      //Element: Element,
      Focus: Focus,
      ReadOnly: ReadOnly,
      Visible: Visible,

      FromAddressDetailsJson: FromAddressDetailsJson,
      ToAddressDetailsJson: ToAddressDetailsJson,

      ShowCity: ShowCity,
      ShowCountry: ShowCountry,
      ShowDeliveryType: ShowDeliveryType,
      ShowInstructions: ShowInstructions,
      ShowPostalId: ShowPostalId,
      ShowPropertyName: ShowPropertyName,

      AdvancedCity: AdvancedCity,
      AdvancedPostalId: AdvancedPostalId,
      AutoValidateAddress: AutoValidateAddress,

      IsDeliveryTypeBagOrBox: IsDeliveryTypeBagOrBox,

      WidthResizeFromParent: WidthResizeFromParent,
    };
    return _self;
  }


  // =============================
  // PUBLIC: BankingDetails object
  // =============================
  function BankingDetails(e, options) {

    var mElement;
    var mInitialised = false;
    var mOptions;
    var mPaymentTypeCategoryFilter = "";
    var mPaymentTypes;
    var mPaymentTypesFiltered;
    var mRecord;
    var mWarningMessage = "";
    var mWarningTimer;

    var C = {
      trPaymentType: null,
      cboPaymentType: null,

      trAccountSortCode: null,
      cboAccountSortCode: null,

      trAccountNumber: null,
      txtAccountNumber: null,

      trName: null,
      txtName: null,

      trCardExpiry: null,
      cboCardExpiryMonth: null,
      cboCardExpiryYear: null,

      trReference: null,
      divReferenceTagsList: null,
      txtReference1: null,
      txtReference2: null,
      txtReference3: null,

      trWarning: null,
      divWarning: null,
    };

    // Extend options with defaults
    BankingDetailsDefaults = {
      allowBlank: false,
      readOnly: false,
      autoReadOnly: true,
      showWarnings: true, // Set to false if showing obfuscated details
      visible: true,

      paymentEntry: false, // Show fields specific to making a payment (rather than just recording banking details)
      historic: false, // Affects how list of Credit Card Expiry Years is built
      resolveReference: false, // Resolve reference tags, e.g., for Payment Entry

      onPaymentTypeChange: null,
    };
    mOptions = $.extend({}, BankingDetailsDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.AccountIncomingPaymentDetails: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Validate Element
    switch (mElement.prop("tagName")) {
      case "TBODY":
        break;

      default:
        console.warn("widget_ui.AccountIncomingPaymentDetails: Element '" + id + "' must be a TBODY element.");
        return;
    }

    // Create sub-elements and controls
    //   Payment Method
    var cid = CreateGuid(true);
    C.trPaymentType = $("<tr style='display:none'><th><label for='" + cid + "'>Type:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trPaymentType);
    C.cboPaymentType = DBCombo($("input", C.trPaymentType), {
      allowBlank: mOptions.allowBlank,
      maxLength: 15,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);

        // Notify
        var e = {};
        if (mOptions.onPaymentTypeChange) mOptions.onPaymentTypeChange(_self, e);
      },
    });
    //    Account Sort Code
    cid += "X";
    C.trAccountSortCode = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Sort Code:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountSortCode);
    C.cboAccountSortCode = DBCombo($("input", C.trAccountSortCode), {
      allowBlank: false,
      maxLength: 10,
      width: "8em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    //    Account Number/ Credit Card Number
    cid += "X";
    C.trAccountNumber = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Account No.:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trAccountNumber);
    C.txtAccountNumber = TextBox($("input", C.trAccountNumber), {
      allowBlank: false,
      maxLength: 30,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    //    Name
    cid += "X";
    C.trName = $("<tr style='display:none'><th><label for='" + cid + "'>Name:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trName);
    C.txtName = TextBox($("input", C.trName), {
      allowBlank: true,
      maxLength: 100,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    //    Card Expiry
    cid += "X";
    C.trCardExpiry = $("<tr style='display:none'><th><nobr><label for='" + cid + "'>Card Expiry:</label>&nbsp;</nobr></th><td><input id='" + cid + "'/> <input id='" + cid + "2'/></td>");
    mElement.append(C.trCardExpiry);
    C.cboCardExpiryMonth = ComboBox($($("input", C.trCardExpiry)[0]), {
      allowBlank: true,
      listCsv: "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
      limitToList: false,
      maxLength: 3,
      width: "4em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.cboCardExpiryMonth.Element().blur(function () {
      // Allow month to be entered as a numeric value
      if (C.cboCardExpiryMonth.Text()) {
        var month = Runtime_ParseNumber(C.cboCardExpiryMonth.Text());
        if (month > 0) {
          // Convert to list value
          C.cboCardExpiryMonth.ListIndex(month - 1);
        }
        else {
          // Limit to list
          if (!C.cboCardExpiryMonth.ListExists(C.cboCardExpiryMonth.Text())) {
            C.cboCardExpiryMonth.Text("");
          }
        }
      }
    });
    C.cboCardExpiryYear = ComboBox($($("input", C.trCardExpiry)[1]), {
      allowBlank: true,
      limitToList: false,
      maxLength: 4,
      width: "5em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.cboCardExpiryYear.Element().blur(function () {
      // Allow 2-digit year entry
      if (C.cboCardExpiryYear.Text()) {
        var year = Runtime_ParseNumber(C.cboCardExpiryYear.Text());
        if (year < 100) year += 2000;
        if (year > 9999) year = 9999;
        C.cboCardExpiryYear.Text(year);
      }
    });
    var arrYears = [];
    var start = new Date().getFullYear(), end = start + 10;
    if (mOptions.historic) start -= 10;
    for (var i = start; i < end; i++) {
      arrYears.push(i + "");
    }
    C.cboCardExpiryYear.ListFromArray(arrYears);
    //    Reference
    cid += "X";
    C.trReference = $("<tr style='display:none'><th><label for='" + cid + "P'>Reference:</label></th><td><div id='" + cid + "TL'></div><input id='" + cid + "P'/> <input id='" + cid + "C'/> <input id='" + cid + "R'/></td>");
    mElement.append(C.trReference);
    C.divReferenceTagsList = $("div", C.trReference);
    C.txtReference1 = TextBox($($("input", C.trReference)[0]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.txtReference2 = TextBox($($("input", C.trReference)[1]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    C.txtReference3 = TextBox($($("input", C.trReference)[2]), {
      allowBlank: true,
      maxLength: 10,
      tagsListElement: C.divReferenceTagsList,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        UpdateElement(true);
      },
    });
    //    Warning
    cid += "X";
    C.trWarning = $("<tr style='display:none'><th colspan='2'><div class='is-info-text info' style='color:darkred; margin-bottom:0 !important; margin-top:0 !important; width:100%'></div></th>");
    mElement.append(C.trWarning);
    C.divWarning = $("div", C.trWarning);

    // Update element
    UpdateElement(false);


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement(refetchWarningMessage) {
      // Initialise
      if (mWarningTimer && (refetchWarningMessage || !C.cboPaymentType.Text())) {
        window.clearTimeout(mWarningTimer);
        mWarningTimer = null;
      }

      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }

      // Layout and Configuration
      // NOTE: Do not arbitrarily hide controls since they lose focus!
      if (!mInitialised) C.trPaymentType.hide();
      if (!mOptions.showWarnings || !mWarningMessage || !C.cboPaymentType.Text()) C.trWarning.hide();

      if (mInitialised) {
        // Layout
        C.trPaymentType.show();
        var paymentTypeCategory = "";
        var paymentType = null;
        if (C.cboPaymentType.ListIndex() != -1) {
          paymentType = mPaymentTypesFiltered[C.cboPaymentType.ListIndex()];
          paymentTypeCategory = paymentType.PaymentTypeCategory;
        }

        // Account Sort Code
        if (mRecord && mRecord.BankSortCodeCaption) {
          if (mRecord.ShowFullAccountSortCodeList) {
            C.cboAccountSortCode.ShowDropdown(true);
            C.cboAccountSortCode.RefreshFromStandardRange("BankBranches");
          }
          else {
            C.cboAccountSortCode.ShowDropdown(false);
          }
        }

        switch (paymentTypeCategory.toUpperCase()) {
          case "":
            // Unknown
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            break;

          case "BANK":
            // Bank Account
            C.trCardExpiry.hide();

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.cboAccountSortCode.Caption(mRecord.BankSortCodeCaption + ":");
              C.trAccountSortCode.show();
            }
            else {
              C.trAccountSortCode.hide();
            }

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Account No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.show();

            if (mRecord) C.txtReference1.BlankTip(mRecord.Reference1Caption);
            if (mRecord) C.txtReference1.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(mRecord && mRecord.Reference1Caption);

            if (mRecord) C.txtReference2.BlankTip(mRecord.Reference2Caption);
            if (mRecord) C.txtReference2.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference2.WidthResizeFromParent();
            C.txtReference2.Visible(mRecord && mRecord.Reference2Caption != null);

            if (mRecord) C.txtReference3.BlankTip(mRecord.Reference3Caption);
            if (mRecord) C.txtReference3.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference3.WidthResizeFromParent();
            C.txtReference3.Visible(mRecord && mRecord.Reference3Caption != null);

            if (mRecord.Reference1Caption && mRecord.Reference2Caption) {
              C.txtReference1.Caption("References:");
            }
            else {
              C.txtReference1.Caption("Reference:");
              C.txtReference1.BlankTip("");
            }
            C.cboAccountSortCode.AllowBlank(false);
            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(true);
            break;

          case "CASH":
            // Cash
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            break;

          case "CHEQUE":
            // Cheque
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();

            C.trName.show();
            C.txtName.Caption("Drawer:");
            C.txtName.WidthResizeFromParent();

            C.txtName.AllowBlank(true);
            break;

          case "CREDITCARD":
            // Credit Card
            C.trAccountSortCode.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Card No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Card Name:");
            C.txtName.WidthResizeFromParent();

            C.trCardExpiry.show();

            C.trReference.show();
            C.txtReference1.BlankTip("");
            C.txtReference1.Caption("Reference:");
            C.txtReference1.MaxLength(50);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(true);
            C.txtReference2.Visible(false);
            C.txtReference3.Visible(false);

            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(false);
            C.cboCardExpiryMonth.AllowBlank(false);
            C.cboCardExpiryYear.AllowBlank(false);
            break;

          case "POSCARD":
            // POS Card
            C.trAccountSortCode.hide();
            C.trReference.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Card No:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Card Name:");
            C.txtName.WidthResizeFromParent();

            C.trCardExpiry.show();

            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(false);
            C.cboCardExpiryMonth.AllowBlank(true);
            C.cboCardExpiryYear.AllowBlank(true);
            break;

          case "TOKEN":
            // Token (like Bank Account but without the same validation)
            C.trAccountSortCode.hide();
            C.trCardExpiry.hide();

            C.trAccountNumber.show();
            C.txtAccountNumber.Caption("Token:");
            C.txtAccountNumber.WidthResizeFromParent();

            C.trName.show();
            C.txtName.Caption("Name:");
            C.txtName.WidthResizeFromParent();

            C.trReference.show();

            if (mRecord) C.txtReference1.BlankTip(mRecord.Reference1Caption);
            if (mRecord) C.txtReference1.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference1.WidthResizeFromParent();
            C.txtReference1.Visible(mRecord && mRecord.Reference1Caption);

            if (mRecord) C.txtReference2.BlankTip(mRecord.Reference2Caption);
            if (mRecord) C.txtReference2.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference2.WidthResizeFromParent();
            C.txtReference2.Visible(mRecord && mRecord.Reference2Caption != null);

            if (mRecord) C.txtReference3.BlankTip(mRecord.Reference3Caption);
            if (mRecord) C.txtReference3.MaxLength(mRecord.ReferenceMaxLength);
            C.txtReference3.WidthResizeFromParent();
            C.txtReference3.Visible(mRecord && mRecord.Reference3Caption != null);

            if (mRecord.Reference1Caption && mRecord.Reference2Caption) {
              C.txtReference1.Caption("References:");
            }
            else {
              C.txtReference1.Caption("Reference:");
              C.txtReference1.BlankTip("");
            }

            C.txtAccountNumber.AllowBlank(false);
            C.txtName.AllowBlank(true);
            break;

          default:
            C.trAccountSortCode.hide();
            C.trAccountNumber.hide();
            C.trName.hide();
            C.trCardExpiry.hide();
            C.trReference.hide();
            window.alert("Unhandled Payment Type Category '" + paymentTypeCategory + "'.");
        }

        // Other
        if (mRecord) {
        }

        // Read-Only
        C.cboPaymentType.ReadOnly(mOptions.readOnly);
        C.cboAccountSortCode.ReadOnly(mOptions.readOnly);
        C.txtAccountNumber.ReadOnly(mOptions.readOnly);
        C.txtName.ReadOnly(mOptions.readOnly);
        C.cboCardExpiryMonth.ReadOnly(mOptions.readOnly);
        C.cboCardExpiryYear.ReadOnly(mOptions.readOnly);
        C.txtReference1.ReadOnly(mOptions.readOnly);
        C.txtReference2.ReadOnly(mOptions.readOnly);
        C.txtReference3.ReadOnly(mOptions.readOnly);

        // Warning
        // NOTE: Also updates Account Number and Sort Code formats if necessary
        if (mOptions.showWarnings && refetchWarningMessage && mRecord && C.cboPaymentType.Text()) {
          mWarningTimer = window.setTimeout(function () {
            mWarningTimer = null;

            // Fetch warning
            var params = { bankingDetailsJson: ToBankingDetailsJson() };

            widget._SystemGetString("BankingDetails_GetValidationDetails", params,
              function (data) {
                if (data) {
                  // Parse
                  data = JSON.parse(data);
                  mWarningMessage = data.Message;

                  // Format Account Number and Sort Code
                  if (!mOptions.readOnly) {
                    if (C.txtAccountNumber.Text() && C.txtAccountNumber.Text() == data.AccountNumberOriginal && data.AccountNumberFormatted) {
                      C.txtAccountNumber.Text(data.AccountNumberFormatted);
                    }

                    if (C.cboAccountSortCode.Text() && C.cboAccountSortCode.Text() == data.AccountSortCodeOriginal && data.AccountSortCodeFormatted) {
                      C.cboAccountSortCode.Text(data.AccountSortCodeFormatted);
                    }
                  }
                }
                else {
                  // Returned nothing!
                  mWarningMessage = "";
                }

                C.divWarning.html(HtmlEncode(mWarningMessage));
                if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
                if (data.Warning) C.divWarning.css("color", "darkred"); else C.divWarning.css("color", "green");
              },

              function (data) {
                mWarningMessage = data;
                widget.RegisterError("widget_ui.AccountIncomingPaymentDetails: Failed to retrieve validation details: " + data);

                C.divWarning.html(HtmlEncode(mWarningMessage));
                if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
              }
            );
          }, 750);
        }
        else {
          if (C.cboPaymentType.Text()) {
            C.divWarning.html(HtmlEncode(mWarningMessage));
            if (mWarningMessage) C.trWarning.show(); else C.trWarning.hide();
          }
          else {
            C.trWarning.hide();
          }
        }
      }
      else {
        if (mWarningMessage) {
          C.divWarning.html(HtmlEncode(mWarningMessage));
        }
        else {
          C.divWarning.css("color", "darkred");
          C.divWarning.text("Initialising, please wait...");
        }
        C.trWarning.show();
      }
    }

    // ------------------
    // PUBLIC: Initialise
    // ------------------
    function Initialise(options) {
      // Extend options with defaults
      var InitialiseDefaults = {
      };
      options = $.extend({}, InitialiseDefaults, options);

      // Initialise
      mInitialised = false;
      mWarningMessage = "";
      if (mWarningTimer) {
        window.clearTimeout(mWarningTimer);
        mWarningTimer = null;
      }
      UpdateElement(false);

      // Reference Tags
      var tags = [];
      if (!mOptions.readOnly) {
        tags = [
          { caption: "Account ID", value: "[AccId]" },
          { caption: "Name", value: "[AccName]" },
          { caption: "External ID", value: "[ExtId]" },
          { caption: "Main Client ID", value: "[ClientId]" },
          { caption: "Last Name", value: "[LastName]" },
          { caption: "Account Type ID", value: "[ATId]" },
          { caption: "Bank Ref Code", value: "[ATCode]" },
        ];
      }
      C.txtReference1.TagsListDefine(tags);
      C.txtReference2.TagsListDefine(tags);
      C.txtReference3.TagsListDefine(tags);

      // Other

      // Get Initialisation details
      var params = {
      };
      widget._SystemGetString("BankingDetails_Initialise", params,
        function (data) {
          if (data) {
            // Parse
            data = JSON.parse(data);
            mRecord = data;
            mPaymentTypes = data.PaymentTypesList;
            mPaymentTypesFiltered = mPaymentTypes;

            // Lists
            PaymentTypeCategoryFilter(mPaymentTypeCategoryFilter);

            // Finalise
            mInitialised = true;
            UpdateElement(true);
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.BankingDetails: Failed to retrieve initialisation details: " + data);
          UpdateElement(false);
        }
      );
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      // Ensure Payment Type is visible
      C.trPaymentType.show();

      C.cboPaymentType.Focus();
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -------------------------
    // PUBLIC: ReadOnly property
    // -------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = value;

          UpdateElement();
        }
      }
    }

    // --------------------------------
    // PUBLIC: PaymentTypeId property
    // --------------------------------
    function PaymentTypeId(value) {
      if (value === undefined) {
        // Get
        return C.cboPaymentType.Text();
      }
      else {
        // Set
        if (value != C.cboPaymentType.Text()) {
          C.cboPaymentType.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // --------------------------------
    // PUBLIC: AccountSortCode property
    // --------------------------------
    function AccountSortCode(value) {
      if (value === undefined) {
        // Get
        return C.cboAccountSortCode.Text();
      }
      else {
        // Set
        if (value != C.cboAccountSortCode.Text()) {
          C.cboAccountSortCode.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ------------------------------
    // PUBLIC: AccountNumber property
    // ------------------------------
    function AccountNumber(value) {
      if (value === undefined) {
        // Get
        return C.txtAccountNumber.Text();
      }
      else {
        // Set
        if (value != C.txtAccountNumber.Text()) {
          C.txtAccountNumber.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ----------------------------
    // PUBLIC: AccountName property
    // ----------------------------
    function AccountName(value) {
      if (value === undefined) {
        // Get
        return C.txtName.Text();
      }
      else {
        // Set
        if (value != C.txtName.Text()) {
          C.txtName.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------------------------------
    // PUBLIC: CardExpiryMonthIndex property (0 = January)
    // ---------------------------------------------------
    function CardExpiryMonthIndex(value) {
      if (value === undefined) {
        // Get
        return C.cboCardExpiryMonth.ListIndex();
      }
      else {
        // Set
        C.cboCardExpiryMonth.ListIndex(value);

        // Update Element
        UpdateElement(true);
      }
    }

    // -------------------------------
    // PUBLIC: CardExpiryYear property
    // -------------------------------
    function CardExpiryYear(value) {
      if (value === undefined) {
        // Get
        return Runtime_ParseNumber(C.cboCardExpiryYear.Text());
      }
      else {
        // Set
        C.cboCardExpiryYear.Text(Runtime_ParseNumber(value));

        // Update Element
        UpdateElement(true);
      }
    }

    // ---------------------------
    // PUBLIC: Reference1 property
    // ---------------------------
    function Reference1(value) {
      if (value === undefined) {
        // Get
        return C.txtReference1.Text();
      }
      else {
        // Set
        if (value != C.txtReference1.Text()) {
          C.txtReference1.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------
    // PUBLIC: Reference2 property
    // ---------------------------
    function Reference2(value) {
      if (value === undefined) {
        // Get
        return C.txtReference2.Text();
      }
      else {
        // Set
        if (value != C.txtReference2.Text()) {
          C.txtReference2.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // ---------------------------
    // PUBLIC: Reference3 property
    // ---------------------------
    function Reference3(value) {
      if (value === undefined) {
        // Get
        return C.txtReference3.Text();
      }
      else {
        // Set
        if (value != C.txtReference3.Text()) {
          C.txtReference3.Text(value);

          // Update Element
          UpdateElement(true);
        }
      }
    }

    // --------------------------------------------------------------------
    // PUBLIC: Update values from a JSON formatted finBankingDetails object
    // --------------------------------------------------------------------
    function FromBankingDetailsJson(json) {
      // Parse
      if (json) {
        try {
          var o = JSON.parse(json);

          // Update fields
          // NOTE: Cash Register is set by its own property - not included in Banking Details
          C.cboPaymentType.Text(o.PaymentTypeId);
          C.cboAccountSortCode.Text(o.AccountSortCode);
          C.txtAccountNumber.Text(o.AccountNumber);
          C.txtName.Text(o.AccountName);
          CardExpiryMonthIndex(o.CardExpiryMonthIndex);
          if (o.CardExpiryYear && o.CardExpiryYear != -1) {
            C.cboCardExpiryYear.Text(o.CardExpiryYear);
          }
          else {
            C.cboCardExpiryYear.Text("");
          }
          C.txtReference1.Text(o.Reference1);
          C.txtReference2.Text(o.Reference2);
          C.txtReference3.Text(o.Reference3);

          // Initialise
          UpdateElement(true);
        }
        catch (ex) {
          console.warn("widget.UI.BankingDetails: Error calling FromBankingDetailsJson: " + ex);
        }
      }
    }

    // -----------------------------------------------------
    // PUBLIC: Get a JSON formatted finBankingDetails object
    // -----------------------------------------------------
    function ToBankingDetailsJson() {
      var o = {};

      // NOTE: Cash Register is retrieved by its own property - not included in Banking Details
      o.PaymentTypeId = C.cboPaymentType.Text();
      o.AccountSortCode = C.cboAccountSortCode.Text();
      o.AccountNumber = C.txtAccountNumber.Text();
      o.AccountName = C.txtName.Text();
      o.CardExpiryMonthIndex = CardExpiryMonthIndex();
      if (C.cboCardExpiryYear.Text()) {
        o.CardExpiryYear = C.cboCardExpiryYear.Text(o.CardExpiryYear);
      }
      else {
        o.CardExpiryYear = -1;
      }
      o.Reference1 = C.txtReference1.Text();
      o.Reference2 = C.txtReference2.Text();
      o.Reference3 = C.txtReference3.Text();

      return JSON.stringify(o);
    }

    // ------------------------------------------
    // PUBLIC: PaymentTypeCategoryFilter property
    // ------------------------------------------
    function PaymentTypeCategoryFilter(value) {
      if (value === undefined) {
        // Get
        return mPaymentTypeCategoryFilter;
      }
      else {
        // Set
        if (!value) value = "";

        mPaymentTypeCategoryFilter = value;

        // Filter Payment Methods list
        mPaymentTypesFiltered = [];
        if (mPaymentTypes) {
          for (var i = 0; i < mPaymentTypes.length; i++) {
            var item = mPaymentTypes[i];

            switch (mPaymentTypeCategoryFilter.toUpperCase()) {
              case "":
                // All
                mPaymentTypesFiltered.push(item);
                break;

              case "DIRECTCREDIT":
                // Special, pseudo-category
                if (item.PaymentFlowDirection == "Outgoing") {
                  switch (item.PaymentTypeCategory.toUpperCase()) {
                    case "BANK":
                    case "TOKEN":
                    case "SPLIT":
                    case "ZEPTONZ":
                      mPaymentTypesFiltered.push(item);
                      break;
                  }
                }
                break;

              default:
                // Named Payment Type Category
                if (item.PaymentTypeCategory == mPaymentTypeCategoryFilter) {
                  mPaymentTypesFiltered.push(item);
                }
                break;
            }

          }
        }

        // Update Control
        C.cboPaymentType.RefreshFromCollection(mPaymentTypesFiltered, "PaymentTypeId", "Description");
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent() {
      C.txtName.WidthResizeFromParent();
      C.txtAccountNumber.WidthResizeFromParent();
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "BankingDetails",

      //AutoReadOnly: AutoReadOnly,
      //Element: Element,
      Focus: Focus,
      Initialise: Initialise,
      ReadOnly: ReadOnly,
      Visible: Visible,

      FromBankingDetailsJson: FromBankingDetailsJson,
      ToBankingDetailsJson: ToBankingDetailsJson,

      PaymentTypeCategoryFilter: PaymentTypeCategoryFilter,
      AccountSortCode: AccountSortCode,
      AccountNumber: AccountNumber,
      AccountName: AccountName,
      CardExpiryMonthIndex: CardExpiryMonthIndex,
      CardExpiryYear: CardExpiryYear,
      Reference1: Reference1,
      Reference2: Reference2,
      Reference3: Reference3,

      WidthResizeFromParent: WidthResizeFromParent,
    };
    return _self;
  }



  // =====================
  // PUBLIC: Button object
  // =====================
  function Button(e, options) {

    var mElement;
    var mEnabled = true;
    var mOptions;

    // Extend options with defaults
    ButtonDefaults = {
      caption: "",
      cssClass: "is-button normal",

      checked: false,
      style: "",
      icon: "",
      tooltipText: "",

      width: "auto",
      visible: true,

      onClick: null
    };
    var mOptions = $.extend({}, ButtonDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("userinterface.Button: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Handle events
    mElement.click(mOptions.onClick);

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Caption
      mElement.text(mOptions.caption);

      // CSS Classes
      switch (mOptions.style.toUpperCase()) {
        case "HYPERLINK":
          break;
        default:
          // Append an extra class to indicate that this is a styled button
          if (mOptions.cssClass == "is-button") mElement.addClass("is-button-styled");
      }
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);
      if (mOptions.style) mElement.addClass(mOptions.style);

      // Icon
      if (mOptions.icon) {
        if (window.$Api) {
          mElement.css("background-image", "url(" + $Api.GetIconUrl(mOptions.icon, 16) + ")");
        }
      }

      // Checked
      if (mOptions.checked) {
        mElement.addClass("checked");
      }
      else {
        mElement.removeClass("checked");
      }

      // Tooltip
      mElement.attr("title", mOptions.tooltipText);

      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }

      // Disabled
      if (mEnabled) {
        mElement.removeAttr("disabled");
      }
      else {
        mElement.attr("disabled", true);
      }

    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        return mElement.text();
      }
      else {
        // Set
        mElement.text(value);
      }
    }

    // ------------------------
    // PUBLIC: Checked property
    // ------------------------
    function Checked(value) {
      if (value === undefined) {
        // Get
        return mOptions.checked;
      }
      else {
        // Set
        mOptions.checked = (value == true);
        UpdateElement();
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // ------------------------
    // PUBLIC: Enabled property
    // ------------------------
    function Enabled(value) {
      if (value === undefined) {
        // Get
        return mEnabled;
      }
      else {
        // Set
        if (value != mEnabled) {
          mEnabled = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "Button",

      Caption: Caption,
      Checked: Checked,
      Element: Element,
      Enabled: Enabled,
      Focus: Focus,
      Visible: Visible
    };
    return _self;
  }



  // =========================
  // PUBLIC: ButtonList object
  // =========================
  function ButtonList(e, options) {
    var mButtons = [];
    var mElement;
    var mElementRow;
    var mOptions;
    var mSelectedItemIndex = -1;

    // Extend options with defaults
    ButtonListDefaults = {
      style: "grid",
      size: "large",
      showCategory: false,
      buttonWidth: null,

      readOnly: false,
      autoReadOnly: true,

      onChange: null,
    };
    mOptions = $.extend({}, ButtonListDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.ButtonList: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Initialise
    UpdateElement();

    // Handle Events
    //mElement.bind("click", NotifyChange);


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Classes
      mElement.addClass("is-button-list");
      mElement.removeClass("grid vertical"); // Remove existing styles
      if (mOptions.style) {
        mElement.addClass(mOptions.style.toLowerCase());
      }
      if (mOptions.size) {
        mElement.addClass(mOptions.size.toLowerCase());
      }

      // Create Buttons
      mElement.children().remove();

      // Assign button objects and index for internal use (for when grouped into categories)
      for (var i = 0; i < mButtons.length; i++) {
        mButtons[i].__index = i;
      }

      // Create list(s)
      if (mOptions.showCategory) {
        // =================
        // Categorised lists
        // =================
        // Get list of Categories
        var categories = [];
        for (var i = 0; i < mButtons.length; i++) {
          var item = mButtons[i];
          if (item.visible) {
            if (categories.indexOf(item.category) == -1) {
              categories.push(item.category);
            }
          }
        }

        // Append categories and lists
        for (var i = 0; i < categories.length; i++) {
          // Get buttons in this category
          var buttons = [];
          for (var j = 0; j < mButtons.length; j++) {
            var item = mButtons[j];
            if (item.category == categories[i]) {
              buttons.push(item);
            }
          }

          // Add category header
          if (categories[i]) {
            mElement.append("<h1>" + HtmlEncode(categories[i]) + "</h1>");
          }

          // Add list
          UpdateElement_AppendList(buttons);
        }
      }
      else {
        // ===========
        // Single list
        // ===========
        UpdateElement_AppendList(mButtons);
      }

      // Read-only?
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
      }
      else {
        mElement.removeClass("is-readonly");
      }

    }

    function UpdateElement_AppendList(buttons) {
      var ul = $("<ul></ul>");
      for (var i = 0; i < buttons.length; i++) {
        var item = buttons[i];
        var li;

        if (item.visible) {
          // Create button
          li = $("<li index='" + item.__index + "'></li>");

          // Overriding button width?
          if (mOptions.buttonWidth) {
            li.css("width", mOptions.buttonWidth);
            li.css("max-width", mOptions.buttonWidth);
            li.css("min-width", "unset");
          }

          // Caption
          var caption = item.caption || "";
          if (caption && caption.toUpperCase().startsWith("<HTML>")) {
            caption = caption.substring(6);
          }
          else {
            caption = widget.UI.HtmlEncode(caption);
            li.attr("title", caption);
          }

          // Icon
          if (item.icon) {
            switch (mOptions.size.toUpperCase()) {
              case "LARGE":
                li.append("<a><img src='" + widget.GetIconUrl(item.icon, 32) + "'/>" + caption + "</a>");
                break;

              default:
                li.append("<a><img src='" + widget.GetIconUrl(item.icon, 16) + "'/>" + caption + "</a>");
                break;
            }
          }
          else {
            li.append("<a>" + caption + "</a>");
          }

          // Priority?
          if (item.priority) {
            li.addClass("important");
            li.css("order", item.PriorityIndex);
          }
          else {
            li.css("order", 999);
          }

          // Selected?
          if (mSelectedItemIndex == item.__index) {
            li.addClass("selected");
          }

          // Get button text
          item._captionText = li.text();

          ul.append(li);
        }
      }

      mElement.append(ul);

      // Handle events
      $("li", ul).click(function (e) {
        if (!mOptions.readOnly) {
          var originalIndex = mSelectedItemIndex;

          // Set index and notify
          SelectedItemIndex($(this).attr("index"));
        }
      });
    }

    // -------------------------------
    // PUBLIC: Button Caption property
    // -------------------------------
    function ButtonCaption(buttonId, caption) {
      // Find button
      var button;
      buttonId = buttonId.toUpperCase();
      for (var i = 0; i < mButtons.length; i++) {
        if (mButtons[i].id.toUpperCase() == buttonId) {
          button = mButtons[i];
          break;
        }
      }
      if (!button) return;

      if (caption === undefined) {
        // Get
        return button.caption;
      }
      else {
        // Set
        if (button.caption != caption) {
          button.caption = caption;
          UpdateElement();
        }
      }
    }

    // -------------------------------------------------------------------------
    // PUBLIC: Get the text of a Button Caption (the caption itself may be HTML)
    // -------------------------------------------------------------------------
    function GetButtonCaptionText(buttonId) {
      // Find button
      var button;
      buttonId = buttonId.toUpperCase();
      for (var i = 0; i < mButtons.length; i++) {
        if (mButtons[i].id.toUpperCase() == buttonId) {
          button = mButtons[i];
          break;
        }
      }
      if (!button) return "";

      return button._captionText || button.caption;
    }

    // -------------------------------
    // PUBLIC: Button Visible property
    // -------------------------------
    function ButtonVisible(buttonId, visible) {
      // Find button
      var button;
      buttonId = buttonId.toUpperCase();
      for (var i = 0; i < mButtons.length; i++) {
        if (mButtons[i].id.toUpperCase() == buttonId) {
          button = mButtons[i];
          break;
        }
      }
      if (!button) return;

      if (visible === undefined) {
        // Get
        return button.visible;
      }
      else {
        // Set
        if (button.visible != visible) {
          button.visible = visible;
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Define Buttons
    // ----------------------
    function ButtonsDefine(buttons) {
      // Initialise
      mButtons = buttons;

      // Normalise
      if (buttons) {
        for (var i = 0; i < buttons.length; i++) {
          var item = buttons[i];
          if (item.visible === undefined) item.visible = true;
        }
      }

      // Update
      UpdateElement();
    }

    // --------------------------
    // PUBLIC: The jQuery Element
    // --------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      if (mOptions.readOnly) return;

      // Notify
      var e = {};
      if (mOptions.onChange) mOptions.onChange(_self, e);
    }

    // ----------------------------------
    // PUBLIC: SelectedItemIndex property
    // ----------------------------------
    function SelectedItemIndex(value, holdEvents) {
      if (value === undefined) {
        // Get
        return mSelectedItemIndex;
      }
      else {
        // Set
        if (value != mSelectedItemIndex) {
          mSelectedItemIndex = value;

          // Update styles
          $("li", mElement).removeClass("selected");
          if (mSelectedItemIndex != -1) {
            $("li[index='" + mSelectedItemIndex + "']", mElement).addClass("selected");
          }

          // Notify?
          if (!holdEvents && mOptions.onChange) mOptions.onChange(_self, {});
        }
      }
    }

    // -------------------------------
    // PUBLIC: SelectedItemId property
    // -------------------------------
    function SelectedItemId(value, holdEvents) {
      if (value === undefined) {
        // Get
        if (mSelectedItemIndex < 0 || mSelectedItemIndex > mButtons.length - 1) {
          return "";
        }
        else {
          return mButtons[mSelectedItemIndex].id;
        }
      }
      else {
        // Set
        var index = -1;

        if (value) {
          value = value.toUpperCase();

          for (var i = 0; i < mButtons.length; i++) {
            if (mButtons[i].id && mButtons[i].id.toUpperCase() == value) {
              index = i;
              break;
            }
          }
        }

        if (index != mSelectedItemIndex) {
          SelectedItemIndex(index, holdEvents);
        }
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        if (mOptions.visible) {
          mElement.show();
        }
        else {
          mElement.hide();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Style property
    // ----------------------
    function Style(value) {
      if (value === undefined) {
        // Get
        return mOptions.style;
      }
      else {
        // Set
        if (value != mOptions.style) {
          mOptions.style = value;

          // Update element
          UpdateElement();
        }
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("ButtonList.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "ButtonList",

      AutoReadOnly: AutoReadOnly,
      ButtonCaption: ButtonCaption,
      ButtonVisible: ButtonVisible,
      ButtonsDefine: ButtonsDefine,
      Element: Element,
      Focus: Focus,
      GetButtonCaptionText: GetButtonCaptionText,
      ReadOnly: ReadOnly,
      SelectedItemId: SelectedItemId,
      SelectedItemIndex: SelectedItemIndex,
      Style: Style,
      Visible: Visible,
      VisibleRow: VisibleRow,
    };
    return _self;
  }



  // ==========================
  // PUBLIC: ButtonStrip object
  // ==========================
  function ButtonStrip(e, options) {
    var mButtons = [];
    var mElement;
    var mOptions;
    var mSelectedItemIndex = -1;

    // Extend options with defaults
    var ButtonStripDefaults = {
      readOnly: false,
      autoReadOnly: true,
      visible: true,

      onButtonClick: null,

      parentControl: null, // Internal use only
    };
    mOptions = $.extend({}, ButtonStripDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.ButtonStrip: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Initialise
    UpdateElement();

    // Handle Events
    //mElement.bind("click", NotifyChange);


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Classes
      mElement.addClass("is-button-strip");

      // Create Buttons
      mElement.children().remove();

      var ul = $("<ul></ul>");
      for (var i = 0; i < mButtons.length; i++) {
        var item = mButtons[i];
        var li;

      if (item.visible) {
          // Create button
          li = $("<li></li>");
          li.attr("itemId", item.id);

          // Caption
          var caption = item.caption || "";
          if (caption && caption.toUpperCase().startsWith("<HTML>")) {
            caption = caption.substring(6);
          }
          else {
            caption = widget.UI.HtmlEncode(caption);
          }

          // Icon
          if (item.icon) {
            li.append("<a><img src='" + widget.GetIconUrl(item.icon, 16) + "'/>" + caption + "</a>");
          }
          else {
            li.append("<a>" + caption + "</a>");
          }

          // Tooltip
          if (item.tooltipText) li.attr("title", item.tooltipText);

          // Checked
          // Not yet implemented!

          // Enabled
          //TODO:

          // Get button text
          item._captionText = li.text();

          ul.append(li);
        }
      }

      mElement.append(ul);

      // Read-only
      if (!mOptions.enabled) {
        mElement.addClass("is-readonly");
      }
      else {
        mElement.removeClass("is-readonly");
      }

      // Handle events
      $("li", ul).click(function (e) {
        if (!mOptions.readOnly) {
          // Notify
          NotifyButtonClick($(this).attr("itemId"));
        }
      });
    }

    // -------------------------------
    // PUBLIC: Button Visible property
    // -------------------------------
    function ButtonVisible(buttonId, visible) {
      // Find button
      var button;
      buttonId = buttonId.toUpperCase();
      for (var i = 0; i < mButtons.length; i++) {
        if (mButtons[i].id.toUpperCase() == buttonId) {
          button = mButtons[i];
          break;
        }
      }
      if (!button) return;

      if (visible === undefined) {
        // Get
        return button.visible;
      }
      else {
        // Set
        if (button.visible != visible) {
          button.visible = visible;
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Define Buttons
    // ----------------------
    function ButtonsDefine(buttons) {
      // Initialise
      mButtons = buttons;

      var ButtonDefaults = {
        caption: "",
        checked: false,
        enabled: true,
        icon: "",
        id: "",
        itemType: "button",
        tooltipText: "",
        visible: true,
      };

      // Normalise
      if (buttons) {
        for (var i = 0; i < buttons.length; i++) {
          buttons[i] = $.extend({}, ButtonDefaults, buttons[i]);
        }
      }

      // Update
      UpdateElement();
    }

    // --------------------------
    // PUBLIC: The jQuery Element
    // --------------------------
    function Element() {
      return mElement;
    }

    // -------------------------
    // Raise OnButtonClick event
    // -------------------------
    function NotifyButtonClick(id) {
      if (mOptions.readOnly) return;

      // Notify
      var e = { id: id };
      if (mOptions.onButtonClick) {
        if (mOptions.parentControl) {
          //if (mOptions.parentControl.Focus) mOptions.parentControl.Focus(); // Don't focus, just in case we need to detect selected text range in parent control
          mOptions.onButtonClick(mOptions.parentControl, e);
        }
        else {
          mOptions.onButtonClick(_self, e);
        }
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        if (mOptions.visible) {
          mElement.show();
        }
        else {
          mElement.hide();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "ButtonStrip",

      AutoReadOnly: AutoReadOnly,
      ButtonVisible: ButtonVisible,
      ButtonsDefine: ButtonsDefine,
      Element: Element,
      ReadOnly: ReadOnly,
      Visible: Visible,
    };
    return _self;
  }


  // ==========================
  // PUBLIC: RadioButton object
  // ==========================
  function RadioButton(e, options) {
    // A shortcut to CheckBox
    options.cssClass = "is-radio-button";
    return CheckBox(e, options);
  }


  // =======================
  // PUBLIC: CheckBox object
  // =======================
  function CheckBox(e, options) {
    var mElement;
    var mElementRow;
    var mIsValid = true;
    var mLabelElement;
    var mOptions;
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;
    var mWrapperElement;

    // Extend options with defaults
    CheckBoxDefaults = {
      allowBlank: true,
      blankValidationMessage: "You must check this box",

      caption: "",
      cssClass: "is-checkbox",

      readOnly: false,
      visible: true,
      captionWrap: false,

      onChange: null,
    };
    mOptions = $.extend({}, CheckBoxDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");

      // Assign an auto-generated id?
      if (!id) {
        id = "chk" + CreateGuid(true);
        $(e).attr("id", id);
      }
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.CheckBox: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);
    if ((mElement.attr("type") + "").toUpperCase() != "CHECKBOX") {
      if (mDisableControlStyling && (mElement.attr("type") + "").toUpperCase() == "RADIO") {
        // External libraries such as Materialize may require this to be defined as "RADIO"
      }
      else {
        console.warn("widget_ui.CheckBox: Element '" + id + "' does not have a type attribute of 'checkbox'.");
      }
    };

    // Flag as created
    mElement.attr("is-created", "y");

    // Wrap element
    if (!mDisableControlStyling) {
      if (mOptions.captionWrap) {
        mElement.wrap("<span class='is-checkbox caption-wrap' controltype='checkbox'/>");
      }
      else {
        mElement.wrap("<span style='white-space:nowrap' class='is-checkbox' controltype='checkbox'/>");
      }
    }
    mWrapperElement = $(mElement.parent());

    // Validation elements
    mValidationElement = $("<label style='display:none' class='is-validation-tip'></label>");
    mWrapperElement.append(mValidationElement);

    // Create label
    if (!mDisableControlStyling) {
      mLabelElement = $("<label for='" + id + "' class='is-no-select'>" + HtmlEncode(mOptions.caption) + "</label>").insertAfter(mElement);
    }

    // Handle events
    mValidationElement.click(function () { Focus(); });

    // Initialise
    UpdateElement();

    // Handle Events
    mElement.bind("click", function () {
      NotifyChange();
    });

    // Enter key moves to next field (finPOWER Connect desktop only)?
    if (widget.Options.enterMovesToNextField) {
      mElement.on("keyup", function (e) {
        if (e.keyCode == 13) TriggerTab($(this));
      });
    }


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      if (mOptions.cssClass) {
        mElement.addClass(mOptions.cssClass);
        if (mLabelElement) mLabelElement.addClass(mOptions.cssClass);
      }

      // Read-only
      // NOTE: Checkboxes do not natively support read-only hence we use the disabled attribute instead
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("disabled", "disabled");
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("disabled");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Validation message
      if (mIsValid) {
        mValidationElement.text("");
        mValidationElement.removeClass("is-block");
        mValidationElement.css({ display: "none" });
        mElement.removeClass("is-invalid");
      }
      else {
        mElement.addClass("is-invalid");
        if (mValidationText) {
          if (mValidationTextIsHtml) {
            mValidationElement.html(mValidationText);
          }
          else {
            mValidationElement.text(mValidationText);
          }
          mValidationElement.css({ display: "flex" });
          mValidationElement.addClass("is-block");
        }
        else {
          mValidationElement.css({ display: "none" });
          mValidationElement.removeClass("is-block");
        }
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
        if (mOptions.caption) {
          mWrapperElement.css("display", "inline-block");
        }
        else {
          // Without this, the vertical alignment may not work, e.g., when in a Repeater control that is using flexbox layout
          mWrapperElement.css("display", "inline-flex");
        }
      }
      else {
        mWrapperElement.hide();
      }
    }

    // --------------------------------------
    // PUBLIC: Add a CSS Class to the element
    // --------------------------------------
    function AddClass(className) {
      mWrapperElement.addClass(className);
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // ----------------------------------
    // FRIEND: The jQuery Wrapper Element
    // ----------------------------------
    function WrapperElement() {
      return mWrapperElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      if (mOptions.readOnly) return;

      // Clear validation message
      ValidationSet(true, "", false);

      // Notify
      var e = {};
      if (mOptions.onChange) mOptions.onChange(_self, e);
    }

    // ----------------------------
    // PUBLIC: Read-Only property
    // ----------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        try {
          return mElement.prop("checked");
        }
        catch (e) {
          return false;
        }
      }
      else {
        // Set
        value = (value == true || value == "True" || value == "true");

        mElement.prop("checked", value);
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.Checkbox.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value === undefined) {
        // Get
        return mOptions.allowBlank;
      }
      else {
        // Set
        if (value != mOptions.allowBlank) {
          mOptions.allowBlank = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------
    // PUBLIC: Validate
    // ----------------
    function Validate() {
      // Initialise
      var message = "";
      var valid = true;

      // Ensure has value
      if (!mOptions.allowBlank && !Value()) {
        valid = false;
        message = mOptions.blankValidationMessage;
      }

      // Update element
      if (valid) {
        ValidationSet(true, "", false);
      }
      else {
        ValidationSet(false, message, false);
      }

      return valid;
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      mIsValid = isValid;
      if (validationText === undefined) mValidationText = ""; else mValidationText = validationText;
      if (validationTextIsHtml === undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

      // Update element
      UpdateElement();
    }

    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "CheckBox",

      AddClass: AddClass,
      AllowBlank: AllowBlank,
      Caption: Caption,
      Element: Element,
      Focus: Focus,
      ReadOnly: ReadOnly,
      Validate: Validate,
      ValidationSet: ValidationSet,
      Value: Value,
      Visible: Visible,
      VisibleRow: VisibleRow,

      // Friend
      WrapperElement: WrapperElement,
    };

    // Associate this control to HTML input element (for container validation)
    mElement.prop("is-control", _self);

    return _self;
  }



  // ========================
  // PUBLIC: CheckList object
  // ========================
  function CheckList(e, options) {

    var mElement;
    var mElementRow;
    var mInternalHoldChangeEvent = 0;
    var mIsSelectElement;
    var mLabelElement;
    var mList = [];
    //var mListHidden = [];
    var mListResolved;
    var mListElement;
    var mOptions;
    var mSorted = false;
    var mTextOriginal = "";
    var mWrapperElement;
    
    // Extend options with defaults
    ListBoxDefaults = {
      allowBlank: true,
      captionElement: "auto",
      cssClass: "is-checklist",

      listCsv: "",

      readOnly: false,
      autoReadOnly: true,

      visible: true,
      width: "auto",

      onChange: null,
      //onItemDblClick: null,
    };
    mOptions = $.extend({}, ListBoxDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("CheckList: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Wrap element
    mElement.wrap("<span style='display:inline-block; padding:0; position:relative; margin:0' controltype='checklist' tabindex='0'/>");
    mWrapperElement = $(mElement.parent());

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Allow focus (i.e., so we can handle key presses etc)
    //mWrapperElement.attr("tabindex", "-1");

    // Add List Element
    mListElement = $("<ul></ul>");
    mWrapperElement.append(mListElement);

    // Initialise
    UpdateElement();
    ListFromCsvString(mOptions.listCsv);
    UpdateList();

    // Handle Events
    //mElement.bind("blur", function (e) {
    //  if (!mOptions.readOnly) {
    //    if (Changed()) {
    //      // Clear value if not in list
    //      if (!ListExists(mElement.val())) {
    //        mElement.val("");
    //      }
    //    }
    //  }
    //});

    //mWrapperElement.bind("keydown", function (e) {
    //  switch (e.keyCode) {
    //    case 38: // Cursor Up
    //      ListIndexChange(-1);
    //      break;

    //    case 40: // Cursor Down
    //      ListIndexChange(1);
    //      break;
    //  }
    //});

    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Classes
      if (mOptions.cssClass) mWrapperElement.addClass(mOptions.cssClass);
      mWrapperElement.addClass("is-no-select");
      if (mLabelElement && mLabelElement.parent().prop("tagName") == "TH") {
        mLabelElement && mLabelElement.parent().addClass("top");
      }

      // Allow Blank
      if (mOptions.allowBlank) {
        mWrapperElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mWrapperElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }

      // Read-only
      mElement.attr("readonly", "readonly"); // Hidden textbox is always read-only
      if (mOptions.readOnly) {
        mWrapperElement.addClass("is-readonly");
      }
      else {
        mWrapperElement.removeClass("is-readonly");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Other
      if (mOptions.width != "auto") mWrapperElement.css({ width: mOptions.width });

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }
    }

    // ---------------
    // Update the List
    // ---------------
    function UpdateList() {
      var options = "";
      var text = mElement.val();

      // Clear existing
      mListElement.children().remove();

      // Sort (plus remove hidden items)
      mListResolved = JSON.parse(JSON.stringify(mList));

      // List
      for (var i = 0; i < mListResolved.length; i++) {
        options += "<li class='is-selectable'>" + HtmlEncode(mListResolved[i]) + "</li>";
      }

      // Finalise
      mListElement.append(options);

      // Handle events
      $("li", mListElement).bind("click", function () {
        if (!mOptions.readOnly) {
          ToggleValue($(this).text());
          UpdateListSelectedItems();
        }
      });

      // Set selected items
      UpdateListSelectedItems();

      // No longer dirty
      mListDirty = false;
    }

    // --------------
    // Toggle a Value
    // --------------
    function ToggleValue(value) {
      // Initialise
      var checkedList = ArrayFromCsvString(mElement.val());
      var found = false;
      var newValueArr = [];

      for (var i = 0; i < checkedList.length; i++) {
        if (value.toUpperCase() == checkedList[i].toUpperCase()) {
          found = true;
        }
        else {
          newValueArr.push(checkedList[i]);
        }
      }
      if (!found) newValueArr.push(value);
      var newValue = widget.ArrayToCsvString(newValueArr);

      if (newValue != mElement.val()) {
        TextSet(newValue, true);
      }
    }

    // ------------------------------------------
    // Update the List's Selected (checked) Items
    // ------------------------------------------
    function UpdateListSelectedItems() {
      // Clear existing
      var lis = $("li", mListElement);
      lis.removeClass("checked");

      // Check items
      var checkedList = ArrayFromCsvString(mElement.val());
      for (var i = 0; i < checkedList.length; i++) {
        var a = checkedList[i].toUpperCase();

        for (var j = 0; j < mListResolved.length; j++) {
          var b = mListResolved[j].toUpperCase();
          if (a == b) $(lis[j]).addClass("checked");
        }
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return mElement.val() != mTextOriginal;
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      // Clear value if not in list (never want to notify with an invalid value by accident)
      //if (mOptions.limitToList && !ListExists(mElement.val())) {
      //  mElement.val("");
      //}

      // Notify
      var e = { ChangeHandled: false, TextOriginal: mTextOriginal };
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset TextOriginal?
      if (e.ChangeHandled) mTextOriginal = mElement.val();
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mWrapperElement.focus();

      var t = window.setTimeout(function () {
        window.clearTimeout(t);
        t = null;

        mWrapperElement.focus();
      }, 10);

    }

    // --------------------------------------------------
    // PUBLIC: Check to see if a value exists in the List
    // --------------------------------------------------
    function ListExists(value, ignoreCase) {
      // Initialise
      ignoreCase = ignoreCase ? true : false;
      value += "";

      if (ignoreCase) {
        value = value.toUpperCase();
        for (var i = 0; i < mList.length; i++) {
          if (mList[i].toUpperCase() == value) return true;
        }
      }
      else {
        for (var i = 0; i < mList.length; i++) {
          if (mList[i] == value) return true;
        }
      }

      return false;
    }

    // ----------------------------------------------------------
    // PUBLIC: Check to see if a checked value exists in the List
    // ----------------------------------------------------------
    function ListExistsChecked(value, ignoreCase) {
      // Initialise
      ignoreCase = ignoreCase ? true : false;      
      value += "";
      if (ignoreCase) value = value.toUpperCase();

      // Check items
      var checkedList = ArrayFromCsvString(mElement.val());
      for (var i = 0; i < checkedList.length; i++) {
        if (ignoreCase) {
          if (value == checkedList[i].toUpperCase()) return true;
        }
        else {
          if (value == checkedList[i]) return true;
        }
      }      

      return false;
    }

    // ------------------------------
    // PUBLIC: Set List from an Array
    // ------------------------------
    function ListFromArray(value) {
      mList = value;
      UpdateList();
    }

    // ----------------------------------
    // PUBLIC: Set List from a CSV String
    // ----------------------------------
    function ListFromCsvString(value) {
      mList = ArrayFromCsvString(value);
      UpdateList();
    }

    // --------------------------------
    // PUBLIC: Get List to a CSV String
    // --------------------------------
    function ListToCsvString() {
      return widget.ArrayToCsvString(mListResolved);
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -----------------------
    // PUBLIC: Sorted property
    // -----------------------
    function Sorted(value) {
      if (value === undefined) {
        // Get
        return mSorted;
      }
      else {
        // Set
        if (value != mSorted) {
          mSorted = (value == true);

          // Update list
          UpdateList();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return Runtime_GetString(mElement);
      }
      else {
        // Set
        if (value != mElement.val()) {
          mInternalHoldChangeEvent += 1;
          mElement.val(value);
          mInternalHoldChangeEvent -= 1;

          UpdateListSelectedItems();
        }

        mTextOriginal = value;
      }
    }

    // -------------------
    // Set text internally
    // -------------------
    function TextSet(value, forceEvent) {
      // Raise OnChange event
      if (value != mElement.val() || forceEvent) {
        // Update text
        mInternalHoldChangeEvent += 1;
        mElement.val(value);
        mInternalHoldChangeEvent -= 1;

        // Notify
        NotifyChange();
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("CheckList.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      //mWrapperElement.hide();
      //var parentWidth = mWrapperElement.parent().innerWidth();
      //mWrapperElement.show();
      //var width = mOptions.width;
      //var maxWidth = "";

      //if (mOptions.maxLength == 0 || mOptions.maxLength >= 100 || fullWidth) {
      //  width = "100%";
      //}
      //else {
      //  maxWidth = (mOptions.maxLength * 0.8) + "em";
      //  width = "100%";
      //}
      //mWrapperElement.css({ width: width, maxWidth: maxWidth });
      //mElement.css({ width: width, maxWidth: maxWidth });
    }

    // ---------------------------------
    // PUBLIC: Resize Height from Parent
    // ---------------------------------
    function HeightResizeFromParent() {
      window.alert("HeightResizeFromParent not implemented!");
      if (mListElement) mListElement.hide();

      // Use a timer so that if multiple list boxes are resized (e.g., on the Report, Export page), things work
      var t = window.setTimeout(function () {
        window.clearTimeout(t);
        t = null;

        var parentHeight;
        if (mElementRow) {
          parentHeight = $("td,th", mElementRow).innerHeight();
        }
        else {
          parentHeight = mWrapperElement.parent().innerHeight();
        }
        mWrapperElement.css({ height: (parentHeight + 0) + "px", overflow: "auto" });
        if (mOptions.visible) mListElement.show();
      }, 100);
      //mWrapperElement.css({ height: "100%", overflow: "auto" });
    }

    // --------------------------------
    // PUBLIC: Set the OnChange handler
    // --------------------------------
    function OnChange(handler) {
      mOptions.onChange = handler;
    }

    // ----------------
    // PUBLIC: Validate
    // ----------------
    function Validate() {
      // Initialise
      var valid = true;

      // Ensure has value
      if (!mOptions.allowBlank && !Text()) {
        valid = false;
      }

      return valid;
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "CheckList",

      AutoReadOnly: AutoReadOnly,
      AllowBlank: AllowBlank,
      Caption: Caption,
      Changed: Changed,
      Element: Element,
      Focus: Focus,
      HeightResizeFromParent: HeightResizeFromParent,
      ListExists: ListExists,
      ListExistsChecked: ListExistsChecked,
      ListFromArray: ListFromArray,
      ListFromCsvString: ListFromCsvString,
      ListToCsvString: ListToCsvString,
      ReadOnly: ReadOnly,
      Sorted: Sorted,
      Text: Text,
      Validate: Validate,
      Visible: Visible,
      VisibleRow: VisibleRow,
      WidthResizeFromParent: WidthResizeFromParent,

      OnChange: OnChange,

      /* Friend (internal use only) */
      WrapperElement: function () { return mWrapperElement; },
    };

    // Associate this control to HTML input element (for container validation)
    mWrapperElement.prop("is-control", _self);

    return _self;
  }



  // =======================
  // PUBLIC: ComboBox object
  // =======================
  function ComboBox(e, options) {

    // Use finPOWER Connect Cloud ComboBox (to respect picker panel etc)
    // NOTE: A special 'forceWidgetControl' is used to ensure grids always create a Widget Control, just in case things get incompatible with finCC in the future
    if (!mDisableProxyControls && !mDisableControlStyling && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI && !(options && options.forceWidgetControl)) {
      if (typeof e == "string") {
        e = $("#" + e);
      }
      e.attr("is-created", "y");
      options.widgetDocument = window.document;
      var c = window.parent.$UI.ComboBox(e, options);
      return c;
    }


    var mButtonElement;
    var mButtonStrip;
    var mDropdownPanel;
    var mDropdownShowing = false;
    var mElement;
    var mElementRow;
    var mInternalHoldChangeEvent = 0;
    var mIsSelectElement;
    var mLabelElement;
    var mList = [];
    var mListDirty = true;
    var mListElement;
    var mOptions;
    var mTextOriginal = "";
    var mWrapperElement;

    // Extend options with defaults
    ComboBoxDefaults = {
      blankTip: "",
      captionElement: "auto",
      cssClass: "is-combobox",

      allowBlank: true,
      allowDropdown: true,
      limitToList: false,
      listCsv: "",

      maxLength: 0,

      readOnly: false,
      autoReadOnly: true,

      visible: true,
      width: "auto",

      onChange: null,
      onButtonClick: null,
      onFormatItem: null,

      usePicker: window.__alwaysUsePickerControls,
      pickerCaption: "",

      // Friend
      onAfterDropdownClosed: null,
    };
    mOptions = $.extend({}, ComboBoxDefaults, options);

    // Force Picker Use
    //if (UI.AlwaysUsePickerControls()) mOptions.usePicker = true;

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("userinterface.ComboBox: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Is Select Element?
    mIsSelectElement = (mElement.prop("tagName") == "SELECT");
    if (mIsSelectElement) {
      if (mDisableControlStyling) {
        // Forced options
        mOptions.allowDropdown = false;
        mOptions.limitToList = true;
      }
      else {
        console.warn("userinterface.ComboBox: Element '" + id + "' is a SELECT element. This is only supported if widget.UI.DisableControlStyling has been set to true.");
      }
    }

    // Flag as created
    mElement.attr("is-created", "y");

    // Wrap element
    if (mDisableControlStyling) {
      //mElement.wrap("<span style='' controltype='combobox'/>");
    }
    else {
      //mElement.wrap("<span style='display:inline-flex; align-items:center; padding:0; position:relative; margin:0' controltype='combobox'/>");
      mElement.wrap("<span style='white-space:nowrap; display:inline-flex; flex-direction:row; position:relative' controltype='combobox'/>");
    }
    mWrapperElement = $(mElement.parent());

    // Dropdown button
    //mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button' style='position:absolute; right:0'/>");
    mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button' style='position:relative;left:1px;top:0'/>");
    if (mOptions.usePicker) {
      mButtonElement.addClass("is-picker");
    }
    mWrapperElement.append(mButtonElement);

    // Dropdown panel
    mDropdownPanel = new DropdownPanel(mWrapperElement, { minWidthElement: mElement });

    // Turn auto-complete and spellcheck off since it interferes with our functionality
    mElement.attr("autocomplete", "off");
    mElement.attr("spellcheck", "false");

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Calculate width if 'auto'
    if (mOptions.width == "auto" && mOptions.maxLength != 0) {
      WidthResizeFromParent();
    }

    // Initialise
    UpdateElement();
    ListFromCsvString(mOptions.listCsv);

    // Update List now?
    if (mIsSelectElement && mOptions.listCsv) {
      UpdateList();
    }

    // Handle Events
    if (mIsSelectElement) {
      mElement.bind("change", function (e) {
        NotifyChange(true);
      });
    }
    else {
      mElement.bind("blur", function (e) {
        if (!mOptions.readOnly && mOptions.limitToList) {
          if (Changed()) {
            // Clear value if not in list
            if (!ListExists(mElement.val())) {
              mElement.val("");
            }

            // Notify
            NotifyChange(false);
          }
        }
      });

      mElement.bind("keydown", function (e) {
        switch (e.keyCode) {
          case 13: // Enter
            if (mOptions.createdForGrid) {
              // Prevent a line break from being entered if this is a textarea such as when editing a grid cell
              e.stopPropagation();
              return false;
            }
            break;

          case 27: // Escape
            if (mDropdownPanel.Visible()) {
              DropdownHide(false);
              return false; // Prevent default key action
            }
            return;

          case 38: // Cursor Up
            if (mDropdownPanel.Visible()) {
              ListIndexChange(-1);
              if (mDropdownPanel.Visible()) UpdateListSelectedItem();
            }
            return false; // Prevent default key action

          case 40: // Cursor Down
            if (mDropdownPanel.Visible()) {
              ListIndexChange(1);
              UpdateListSelectedItem();
            }
            else if (!mOptions.readOnly) {
              DropdownShow();
            }
            return false; // Prevent default key action
        }
      });

      mElement.bind("keyup", function (e) {
        var moveX = 0;

        switch (e.keyCode) {
          case 13: // Enter
            if (mDropdownPanel.Visible()) DropdownHide(true);

            // Prevent enter key from propagating, e.g., re-showing the dropdown when displayed in a grid
            e.stopPropagation();

            return false; // Prevent default key action

          case 46: // Delete
            if (mOptions.readOnly) {
              // Read-Only?
              return false;
            }
            else if (mOptions.limitToList) {
              // Value will be cleared later
            }
            else {
              moveX = -1;
            }
            break;

          case 8: // Backspace
            if (mOptions.readOnly) {
              // Read-Only?
              return false;
            }
            else {
              moveX = -1;
            }
            break;

          default:
            if (e.keyCode < 48) return;
            break;
        }

        // Just in case!
        if (mOptions.readOnly) return false;

        // Get list index
        var index = GetMatchIndex(mElement.val(), false);

        // Highlight selected item
        if (mDropdownPanel.Visible()) UpdateListSelectedItem();

        // Partial match?
        if (index == -1 && mOptions.limitToList && e.keyCode == 46) {
          // Clear if Delete pressed, no match and limit to list
          TextSet("", false, false);
          NotifyChange(false);
        }
        else if (index == -1) {
          // Adjust cursor pos
          var x = mElement[0].selectionStart + moveX;
          if (x < 0) x = 0;

          // Partial match
          index = GetMatchIndex(mElement.val(), true);
          if (index != -1) {
            // Highlight matched portion
            if (!mOptions.limitToList && (e.keyCode == 46 || e.keyCode == 8)) {
              // Allow deletion of characters 
            }
            else {
              mElement.val(mList[index]);
              mElement[0].selectionStart = x;
              mElement[0].selectionEnd = 1000;
            }

            NotifyChange(false);
          }
          else if (mOptions.limitToList) {
            // Not in list so clear
            TextSet("", false, false);
            NotifyChange(false);
          }
          else {
            if (Changed()) {
              NotifyChange(false);
            }
          }
        }
      });

      mButtonElement.bind("click", function () {
        if (!mOptions.readOnly) {
          if (mDropdownPanel.Visible())
            DropdownHide(true);
          else
            DropdownShow();
        }
      });
    }

    // Enter key moves to next field (finPOWER Connect desktop only)?
    if (widget.Options.enterMovesToNextField && !mOptions.onEnterKey && !mOptions.multiLine) {
      mElement.on("keyup", function (e) {
        if (e.keyCode == 13) TriggerTab($(this));
      });
    }


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // Allow Blank
      if (mOptions.allowBlank) {
        mElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }
      mElement.attr("placeholder", mOptions.blankTip);

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("readonly");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Show Dropdown?
      if (mOptions.allowDropdown) {
        mButtonElement.show();
      }
      else {
        mButtonElement.hide();
      }

      // Other
      mElement.attr("maxLength", mOptions.maxLength == 0 ? "" : mOptions.maxLength);
      mElement.attr("spellcheck", "false");
      if (mOptions.width != "auto") {
        mElement.css({ width: mOptions.width });
        if (mOptions.width && mOptions.width.endsWith("%")) {
          // If percentage then must also apply width to wrapper
          mWrapperElement.css({ width: mOptions.width });
        }
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
        if (mLabelElement) mLabelElement.show();
      }
      else {
        if (mLabelElement) mLabelElement.hide();
        mWrapperElement.hide();
      }

      // Grid editor?
      if (mOptions.createdForGrid) {
        // Hide dropdown button
        mButtonElement.hide();
      }
    }

    // ---------------
    // Update the List
    // ---------------
    function UpdateList() {
      var options;
      var text = mElement.val();

      // Is Select Element?
      if (mIsSelectElement) {
        UpdateList_SelectElement();
        return;
      }

      // Clear existing
      mDropdownPanel.Clear();

      // Initialise
      options = "<ul>";

      //// Always include a blank row if using a picker
      //window.alert("here: " + mOptions.usePicker);
      //if (mOptions.usePicker) {
      //  options += "<li class='is-selectable'>(clear)</li>"
      //}

      // List
      for (var i = 0; i < mList.length; i++) {
        // Custom formatter (assume HTML by default)
        if (mOptions.onFormatItem) {
          var s = mList[i];
          var e = { value: s, listIndex: i, displayValue: s, displayValueIsHtml: true };
          mOptions.onFormatItem(_self, e);

          s = e.displayValue;
          if (!e.displayValueIsHtml) s = widget.UI.HtmlEncode(s);

          options += "<li class='is-selectable' style='min-height:20px' value='" + widget.UI.HtmlEncode(mList[i]) + "'>" + s + "</li>";
        }
        else {
          options += "<li class='is-selectable' style='min-height:20px'>" + widget.UI.HtmlEncode(mList[i]) + "</li>";
        }
      }

      // Finalise
      options += "</ul>";
      mListElement = $(options);

      // Handle events
      $("li", mListElement).bind("click", function () {
        mElement.val($(this).attr("value") || $(this).text());
        if (!mOptions.usePicker) {
          //if (mOptions.createdForGrid) {
          //  // In a Grid so don't hide and focus back to input
          //}
          //else {
          DropdownHide(true);
          //}
        }
        if (Changed()) NotifyChange(true);
        if (mOptions.usePicker) {
          UpdateListSelectedItem();
          SharedPickerPanel().Hide(true);
        }
      });

      // Append
      if (!mOptions.usePicker) mDropdownPanel.Append(mListElement);

      // No longer dirty
      mListDirty = false;
    }

    function UpdateList_SelectElement() {
      var text = mElement.val();

      // Remove children
      mElement.children().remove();

      // Add items
      for (var i = 0; i < mList.length; i++) {
        mElement.append("<option>" + HtmlEncode(mList[i]) + "</option>");
      }

      // Restore value
      mElement.val(text);
    }

    // -------------------------------
    // Update the List's Selected Item
    // -------------------------------
    function UpdateListSelectedItem() {
      var i = GetMatchIndex(mElement.val(), false);

      // Initialise
      $("li.is-sel", mListElement).removeClass("is-sel");

      // Highlight selected
      if (i >= 0 && i < mList.length) {
        // Highlight
        var e = $($("li", mListElement)[i]);
        e.addClass("is-sel");

        // Ensure visible
        if (mOptions.createdForGrid) {
          // Do not scroll into view since this may mess up grid's vertical scroll position
        }
        else {
          e.ScrollElementIntoView(true);
        }
      }
    }

    // ---------------------
    // PUBLIC: Show Dropdown
    // ---------------------
    function DropdownShow() {
      // Update List
      if (mListDirty) UpdateList();

      // Show
      if (mOptions.usePicker) {
        // ------------
        // Picker Panel
        // ------------
        // Get Caption
        var caption = mOptions.pickerCaption;
        if (!caption && mLabelElement) {
          caption = mLabelElement.text();
          if (caption) {
            caption = "Select " + caption;
            if (caption.endsWith(":")) caption = caption.substr(0, caption.length - 1);

          }
        }
        if (!caption) caption = "Select Item";

        // Show Picker Panel
        SharedPickerPanel().Toggle({
          closeFocusElement: _self,
          sourceButtonElement: mButtonElement,
          caption: caption,
          contentElement: mListElement,

          onKeyDown: function (e) {
            switch (e.keyCode) {
              case 35: // End
                ListIndex(mList.length - 1);
                UpdateListSelectedItem();
                break;

              case 36: // Home
                ListIndex(0);
                UpdateListSelectedItem();
                break;

              case 38: // Cursor Up
                ListIndexChange(-1);
                UpdateListSelectedItem();
                break;

              case 40: // Cursor Down
                ListIndexChange(1);
                UpdateListSelectedItem();
                break;
            }
          }
        });
      }
      else {
        // -------------
        // Dropdown List
        // -------------
        mDropdownPanel.AttachedControl(_self);
        mDropdownPanel.Show();

        // Focus TextBox
        if (!mIsSmallMobileBrowser) {
          mElement.focus();
          mElement.select();
        }
      }

      // Highlight selected item in list
      UpdateListSelectedItem();

      // Showing
      mDropdownShowing = true;
    }

    // ----------------------------
    // PUBLIC: Is Dropdown Showing?
    // ----------------------------
    function DropdownShowing() {
      return mDropdownShowing;
    }

    // ---------------------
    // PUBLIC: Hide Dropdown
    // ---------------------
    function DropdownHide(focus) {
      if (mOptions.usePicker) {
        SharedPickerPanel().Hide();
      }
      else {
        mDropdownPanel.Hide();

        if (focus) {
          mElement.focus();
          mElement.select();
        }
      }

      // Not Showing
      mDropdownShowing = false;

      // Notify (Friend for grid)
      if (mOptions.onAfterDropdownClosed) {
        mOptions.onAfterDropdownClosed(_self, {});
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return mElement.val() != mTextOriginal;
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange(changedFromPopup) {
      // Clear value if not in list (never want to notify with an invalid value by accident)
      if (!mIsSelectElement) {
        if (mOptions.limitToList && !ListExists(mElement.val())) {
          mElement.val("");
        }
      }

      // Notify
      var e = { ChangeHandled: false, TextOriginal: mTextOriginal, ChangedFromPopup: changedFromPopup };
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset TextOriginal?
      if (e.ChangeHandled) mTextOriginal = mElement.val();
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value === undefined) {
        // Get
        return mOptions.allowBlank;
      }
      else {
        // Set
        if (value != mOptions.allowBlank) {
          mOptions.allowBlank = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------
    // PUBLIC: BlankTip property
    // -------------------------
    function BlankTip(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankTip;
      }
      else {
        // Set
        mOptions.blankTip = value;

        // Update element
        UpdateElement();
      }
    }

    // ---------------
    // PU8LIC: Buttons
    // ---------------
    function Buttons() {
      if (!mButtonStrip) {
        // Buttons
        var ebl = $("<div></div>");
        mWrapperElement.append(ebl);
        mButtonStrip = ButtonStrip(ebl, {
          onButtonClick: mOptions.onButtonClick,
          visible: false,
          parentControl: _self,
        });
      }

      return mButtonStrip;
    }

    // ----------------------
    // PUBLIC: Define Buttons
    // ----------------------
    function ButtonsDefine(buttons) {
      // Get Button Strip (created on-demand)
      var bs = Buttons();

      // Define
      if (!buttons) buttons = [];
      bs.ButtonsDefine(buttons);

      // Show
      mButtonStrip.Visible(buttons.length != 0);
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // ----------------
    // Find Match Index
    // ----------------
    function GetMatchIndex(value, partial) {
      if (partial && value.length == 0) return -1;

      for (var i = 0; i < mList.length; i++) {
        if (partial) {
          if (mList[i].substr(0, value.length).toUpperCase() == value.toUpperCase()) return i;
        }
        else {
          if (mList[i] == value) return i;
        }
      }

      return -1;
    }

    // ---------------------------
    // PUBLIC: List Index property
    // ---------------------------
    function ListIndex(value) {
      if (value === undefined) {
        // Get
        return GetMatchIndex(mElement.val(), false);
      }
      else {
        // Set
        if (value < 0 || value > mList.length - 1) {
          Text("");
        }
        else {
          Text(mList[value]);
        }

        mTextOriginal = mElement.val();
      }
    }

    // -----------------
    // Change List Index
    // -----------------
    function ListIndexChange(i) {
      // Increment/ Decrement
      var index = ListIndex() + i;
      if (index < 0) {
        index = 0;
      }
      else if (index > mList.length - 1) {
        index = mList.length - 1;
      }

      // Update Text
      TextSet(mList[index], false, true);
    }

    // ------------------------------
    // PUBLIC: Limit To List property
    // ------------------------------
    function LimitToList(value) {
      if (value != mOptions.limitToList) {
        mOptions.limitToList = (value == true);
      }
    }

    // --------------------------------------------------
    // PUBLIC: Check to see if a value exists in the List
    // --------------------------------------------------
    function ListExists(value, ignoreCase) {
      // Initialise
      ignoreCase = ignoreCase ? true : false;
      value += "";

      if (ignoreCase) {
        value = value.toUpperCase();
        for (var i = 0; i < mList.length; i++) {
          if (mList[i].toUpperCase() == value) return true;
        }
      }
      else {
        for (var i = 0; i < mList.length; i++) {
          if (mList[i] == value) return true;
        }
      }

      return false;
    }

    // -------------------------------
    // PUBLIC: Add a value to the List
    // -------------------------------
    function ListAdd(value) {
      if (!mList) mList = [];
      mList.push(value);
      mListDirty = true;

      // Rebuild list immediately?
      if (mIsSelectElement) UpdateList_SelectElement();
    }

    // ------------------------------
    // PUBLIC: Set List from an Array
    // ------------------------------
    function ListFromArray(value) {
      mList = value;
      mListDirty = true;

      // Rebuild list immediately?
      if (mIsSelectElement) UpdateList_SelectElement();
    }

    // ---------------------------------------------
    // PUBLIC: Set List from a Code Description List
    // ---------------------------------------------
    function ListFromCodeDescriptionList(value) {
      // May be passed across as a JSON String
      if (typeof value == "string") value = JSON.parse(value);

      ListFromCollection(value, "Description");
    }

    // --------------------------------
    // PUBLIC: Set List from Collection
    // --------------------------------
    function ListFromCollection(value, displayColumn) {
      mList = [];
      mListDirty = true;

      if (value != undefined && displayColumn) {
        for (var i = 0; i < value.length; i++) {
          var v = value[i][displayColumn];
          if (v === null || v === undefined) v = "";
          mList.push(v);
        }
      }

      // Rebuild list immediately?
      if (mIsSelectElement) UpdateList_SelectElement();
    }

    // ----------------------------------
    // PUBLIC: Set List from a CSV String
    // ----------------------------------
    function ListFromCsvString(value) {
      mList = ArrayFromCsvString(value);
      mListDirty = true;

      // Rebuild list immediately?
      if (mIsSelectElement) UpdateList_SelectElement();
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ------------------------------
    // PUBLIC: AllowDropdown property
    // ------------------------------
    function AllowDropdown(value) {
      if (value === undefined) {
        // Get
        return mOptions.allowDropdown;
      }
      else {
        // Set
        if (value != mOptions.allowDropdown) {
          mOptions.allowDropdown = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        if (mIsSelectElement) {
          return "" + mElement.val();
        }
        else {
          return Runtime_GetString(mElement);
        }
      }
      else {
        // Set
        if (value != mElement.val()) {
          mInternalHoldChangeEvent += 1;
          mElement.val(value);
          mInternalHoldChangeEvent -= 1;
        }

        mTextOriginal = value;
      }
    }

    // -------------------
    // Set text internally
    // -------------------
    function TextSet(value, forceEvent, changedFromPopup) {
      // Raise OnChange event
      if (value != mElement.val() || forceEvent) {
        // Update text
        mInternalHoldChangeEvent += 1;
        mElement.val(value);
        mInternalHoldChangeEvent -= 1;

        // Notify
        NotifyChange(changedFromPopup);
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("ComboBox.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      mWrapperElement.hide();
      var parentWidth = mWrapperElement.parent().innerWidth();
      mWrapperElement.show();
      var width = mOptions.width;
      var maxWidth = "";

      if (mOptions.maxLength == 0 || mOptions.maxLength > 100 || fullWidth) {
        width = "100%";
      }
      else {
        if (mOptions.maxLength <= 3) {
          maxWidth = ((mOptions.maxLength * 0.8) + 3) + "em"; // Add 3 to account for the dropdown button
        }
        else {
          maxWidth = (mOptions.maxLength * 0.8) + "em";
        }
        width = "100%";
      }
      mWrapperElement.css({ width: width, maxWidth: maxWidth });
      mElement.css({ width: width, maxWidth: maxWidth });

      // Finalise
      if (!mOptions.visible) mWrapperElement.hide();
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "ComboBox",

      AllowBlank: AllowBlank,
      AllowDropdown: AllowDropdown,
      AutoReadOnly: AutoReadOnly,
      BlankTip: BlankTip,
      Buttons: Buttons,
      ButtonsDefine: ButtonsDefine,
      Caption: Caption,
      Changed: Changed,
      DropdownHide: DropdownHide,
      DropdownShow: DropdownShow,
      DropdownShowing: DropdownShowing,
      Element: Element,
      Focus: Focus,
      ListAdd: ListAdd,
      LimitToList: LimitToList,
      ListExists: ListExists,
      ListFromArray: ListFromArray,
      ListFromCodeDescriptionList: ListFromCodeDescriptionList,
      ListFromCollection: ListFromCollection,
      ListFromCsvString: ListFromCsvString,
      ListIndex: ListIndex,
      ReadOnly: ReadOnly,
      Text: Text,
      Visible: Visible,
      VisibleRow: VisibleRow,
      WidthResizeFromParent: WidthResizeFromParent,

      /* Friend (internal use only) */
      WrapperElement: function () { return mWrapperElement; },
      UpdateElement: UpdateElement,
    };
    return _self;
  }



  // ===============================
  // PUBLIC: Dashboard Layout object
  // ===============================
  function DashboardLayout(e, options) {

    var mContainerElement;
    var mColumns = [];
    var mElement;
    var mHeadingElement;

    var mColumnContainer;

    // Get container (may be element or id)
    if (typeof e == "string") e = $("#" + e);
    mContainerElement = e;

    // Initialise
    mElement = $("<div class='is-dashboard-container'></div>");
    mContainerElement.append(mElement);


    // ------------------
    // PUBLIC: Add Column
    // ------------------
    function AddColumn(column, panels) {
      // Start column container?
      if (!mColumnContainer) {
        mColumnContainer = $("<div class='column-container'></div>");
        mElement.append(mColumnContainer);
      }

      // Create column
      var columnElement = $("<div class='column'></div>");
      if (column.width) columnElement.css("width", column.width);
      if (column.maxWidth) columnElement.css("max-width", column.maxWidth);
      if (column.minWidth) columnElement.css("min-width", column.minWidth);

      // Add Column
      mColumns.push(columnElement);
      mColumnContainer.append(columnElement);
      if (mColumns.length == 1) columnElement.addClass("first");

      // Add Panels
      if (panels && panels.length != 0) {
        var panelHeight = 100 / panels.length;

        for (var i = 0; i < panels.length; i++) {
          var panel = panels[i];
          var element = panel.element;
          var headingElement = panel.headingElement;
          var position = panel.position;
          if (typeof element == "string") element = $("#" + element);
          if (typeof headingElement == "string") headingElement = $("#" + headingElement);

          element.css("padding-top", "none");

          var panelElement = $("<div class='panel'></div>");
          columnElement.append(panelElement);

          if (headingElement) {
            var panelHeading = $("<div class='panel-heading'></div>");
            panelElement.append(panelHeading);
            panelHeading.append(headingElement);
          }
          var panelBody = $("<div class='panel-body'></div>");
          panelElement.append(panelBody);
          panelBody.append(element);
          if (panel.align) panelBody.addClass("align-" + panel.align.toLowerCase());
          panel.panelElement = panelElement;

          if (i == 0) panelElement.addClass("first");
          if (panel.maxHeight) panelElement.css("max-height", panel.maxHeight);
          if (panel.visible == false) panelElement.hide();
          if (i < panels.length) panelElement.css("height", panelHeight + "%");

          // Zoomable support
          if (panel.zoomable) {
            var zoomButton = $("<div class='panel-zoom' title='Zoom'></div>");
            panelElement.append(zoomButton);

            (function (p, z) {
              z.click(function () {
                if (p.panelElement.hasClass("zoomed")) {
                  // Unzoom
                  p.panelElement.removeClass("zoomed zooming");
                  z.attr("title", "Zoom");
                  if (p.maxHeight) p.panelElement.css("max-height", p.maxHeight);
                  var t = window.setTimeout(function () {
                    window.clearTimeout(t);
                    t = null;

                    p.panelElement.removeClass("zooming");
                  }, 500);

                  // Notify
                  if (p.onZoomOut) p.onZoomOut();
                }
                else {
                  // Zoom
                  p.panelElement.addClass("zoomed zooming");
                  z.attr("title", "Unzoom");
                  if (p.maxHeight) p.panelElement.css("max-height", "");

                  // Notify
                  if (p.onZoomIn) p.onZoomIn();
                }
              });
            })(panel, zoomButton);
          }
        }
      }
    }

    // -------------------
    // PUBLIC: Add Heading
    // -------------------
    function AddHeading(e) {
      // End column container?
      if (mColumnContainer) {
        mColumnContainer = null;
      }

      if (typeof e == "string") e = $("#" + e);

      if (!mHeadingElement) {
        mHeadingElement = $("<div class='heading'></div>");
        mElement.append(mHeadingElement);
      }

      // Append
      mHeadingElement.append(e);
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "DashboardLayout",

      AddColumn: AddColumn,
      AddHeading: AddHeading,
    };
    return _self;
  }



  // ======================
  // PUBLIC: DateBox object
  // ======================
  function DateBox(e, options) {

    // Use finPOWER Connect Cloud DateBox (to respect picker panel etc)
    if (!mDisableProxyControls && !mDisableControlStyling && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      if (typeof e == "string") {
        e = $("#" + e);
      }
      e.attr("is-created", "y");
      options.widgetDocument = window.document;
      var d = new window.parent.$UI.DateBox(e, options);
      return d;
    }


    var mButtonElement;
    var mCalendar;
    var mDescriptionElement;
    var mDropdownPanel;
    var mElement;
    var mElementRow;
    var mElementTime;
    var mHasFocus = false;
    var mIsDateField = false; // Is this a true HTML 5 date type field?
    var mIsValid = true;
    var mLabelElement;
    var mOptions;
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;
    var mValue = null;
    var mValueOriginal = null;
    var mValueOriginalTime = "";
    var mWrapperElement;

    // Extend options with defaults
    DateBoxDefaults = {
      blankTip: "",
      captionElement: "auto",
      cssClass: "is-datebox",

      allowBlank: true,
      allowDropdown: true,
      allowTime: false,

      historic: false,

      valueIsUtc: false,  // Set to true if hosting a UTC date so that it is displayed in local time, if false, the date will be formatted with the exact UTC values, i.e., not converted to local time

      maxValue: null,
      minValue: null,

      ignoreMinMaxWhenNullValue: true,

      readOnly: false,
      autoReadOnly: true,

      showWeekDayName: false,
      showAge: false,

      width: "auto",
      visible: true,

      onChange: null,
    };
    mOptions = $.extend({}, DateBoxDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.DateBox: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);
    if (mElement[0].tagName != "INPUT") {
      console.warn("widget_ui.DateBox: Element '" + id + "' must be an INPUT type Element.");
    };

    // Flag as created
    mElement.attr("is-created", "y");

    // Wrap element
    if (mDisableControlStyling && !mOptions.allowDropdown) {
    }
    else if (mDisableControlStyling) {
      mElement.wrap("<span style='' controltype='datebox'/>");
    }
    else {
      //mElement.wrap("<span style='display:inline-flex; align-items:center; padding:0; position:relative; margin:0' controltype='datebox'/>");
      mElement.wrap("<span style='white-space:nowrap; display:inline-flex; flex-direction:row' controltype='datebox'/>");
    }
    mWrapperElement = $(mElement.parent());

    // Dropdown button
    if (mDisableControlStyling) {
      mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button'/>");
    }
    else {
      //mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button' style='position:absolute; margin-left:-20px'/>");
      //mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button' style='position:relative;left:1px;top:0'/>");
      mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button'/>");
    }
    if (mOptions.usePicker) {
      mButtonElement.addClass("is-picker");
    }
    mWrapperElement.append(mButtonElement);

    // Time portion
    if (mOptions.allowTime) {
      // NOTE: Not using the standard TimeBox control therefore cancel any right-hand padding that is defined in the CSS to make room for a dropdown button
      mElementTime = $("<input class='is-timebox' style='width:6em;margin-left:4px;text-align:right;padding-right:2px !important' placeholder='Time'/>");
      mWrapperElement.append(mElementTime);
    }

    // Validation elements
    mValidationElement = $("<label style='display:none; position:relative' class='is-combobox is-validation-tip'></label>");
    mWrapperElement.append(mValidationElement);

    // Dropdown panel
    mDropdownPanel = new DropdownPanel(mWrapperElement, { minWidthElement: mElement, cssClass: "is-dropdown is-dropdown-calendar" });

    // Description element
    mDescriptionElement = $("<label class='is-combobox' style='display:none; position:relative'></label>");
    mDescriptionElement.insertAfter(mButtonElement);

    // Turn auto-complete and spellcheck off since it interferes with our functionality
    mElement.attr("autocomplete", "off");
    mElement.attr("spellcheck", "false");

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Initialise
    UpdateElement();

    // Calculate width if 'auto'
    if (mOptions.width == "auto") {
      WidthResizeFromParent();
    }

    // Handle events to format/ unformat values and fire OnChange event
    if (mIsDateField) {
      mElement.blur(function () {
        // Initialise
        mHasFocus = false;

        // Format
        //UpdateText();
      });
      mElement.focus(function () {
        // Initialise
        mHasFocus = true;

        // Unformat for editing
        // Not allowed for HTML 5 date type fields
      });
    }
    else {
      mElement.blur(function () {
        // Initialise
        mHasFocus = false;

        // Parse
        //UpdateText();
      });
      mElement.focus(function () {
        // Initialise
        mHasFocus = true;
      });
    }
    mElement.blur(function () {
      if (!mOptions.readOnly) {
        if (mIsDateField) {
          mValue = mElement[0].valueAsDate;
        }
        else {
          TextToValue(mElement.val());
        }
      }
      if (Changed()) {
        NotifyChange();
      }
      mValueOriginal = mValue;

      // Format
      UpdateText();
    });

    mButtonElement.bind("click", function () {
      if (!mOptions.readOnly) {
        if (mDropdownPanel.Visible())
          DropdownHide(true);
        else
          DropdownShow();
      }
    });

    if (mElementTime) {
      mElementTime.focus(function () {
        // Initialise
        mHasFocus = true;
        mValueOriginalTime = mElementTime.val();
      });

      mElementTime.blur(function () {
        // Initialise
        mHasFocus = false;

        if (!mOptions.readOnly) {
          // Format
          var d = widget.ParseTime(mElementTime.val(), true);
          mElementTime.val(widget.FormatTime(d, true, true));

          if (mValueOriginalTime != mElementTime.val()) {
            NotifyChange();
          }

          mValueOriginalTime = mElementTime.val();
        }
      });
    }

    // Enter key moves to next field (finPOWER Connect desktop only)?
    if (widget.Options.enterMovesToNextField) {
      mElement.on("keyup", function (e) {
        if (e.keyCode == 13) TriggerTab($(this));
      });
      if (mElementTime) {
        mElementTime.on("keyup", function (e) {
          if (e.keyCode == 13) TriggerTab($(this));
        });
      }
    }


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // Allow Blank
      if (mOptions.allowBlank) {
        mElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }
      if (mDisableControlStyling) {
        // Setting blank tip to blank affects: Material Design Lite
        if (mOptions.blankTip) mElement.attr("placeholder", mOptions.blankTip);
      }
      else {
        mElement.attr("placeholder", mOptions.blankTip);
      }

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
        mButtonElement.hide();
        if (mElementTime) {
          mElementTime.addClass("is-readonly");
          mElementTime.attr("readonly", "readonly");
        }
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("readonly");
        mButtonElement.show();
        //mButtonElement.css("display", "inline-block");  // Beware when reinstating this line since it may cause issues in Portals and External Widgets
        if (mElementTime) {
          mElementTime.removeClass("is-readonly");
          mElementTime.removeAttr("readonly", "readonly");
        }
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
        if (mElementTime) mElementTime.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
        if (mElementTime) mElementTime.removeAttr("autoreadonly");
      }

      // Never show button?
      if (!mOptions.allowDropdown) {
        mButtonElement.hide();
      }

      // Other
      mElement.attr("maxLength", mOptions.maxLength == 0 ? "" : mOptions.maxLength);
      if (mOptions.width != "auto") mElement.css({ width: mOptions.width });
      mElement.attr("spellcheck", "false");

      // Description Element
      if (mOptions.showAge || mOptions.showWeekDayName) {
        mDescriptionElement.show();
      }
      else {
        mDescriptionElement.hide();
      }

      // Validation message
      if (mIsValid) {
        mValidationElement.css({ display: "none" });
        mElement.removeClass("is-invalid");
      }
      else {
        mElement.addClass("is-invalid");
        if (mValidationText) {
          if (mValidationTextIsHtml) {
            mValidationElement.html(mValidationText);
          }
          else {
            mValidationElement.text(mValidationText);
          }
          mValidationElement.css({ display: "flex" });
        }
        else {
          mValidationElement.css({ display: "none" });
        }
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
        if (mElementTime) mElementTime.show();
      }
      else {
        mWrapperElement.hide();
        if (mElementTime) mElementTime.hide();
      }
    }

    // ---------------------
    // PUBLIC: Show Dropdown
    // ---------------------
    function DropdownShow() {
      // Update List
      if (!mCalendar) {
        // Create Calendar
        var eCalendar = $("<div></div>");
        mCalendar = new Calendar(eCalendar, {
          showButtons: true,
          standalone: false,

          onChange: function (source, e) {
            var closeDropdown = (e.CloseDropdown || e.CloseDropdown === undefined);

            if (!mCalendar.Value()) {
              TextToValue("");
            }
            else {
              // Use date parsing to avoid UTC and other issues
              TextToValue(Runtime_FormatDate(mCalendar.Value(), false, false, false));

            }
            if (closeDropdown) DropdownHide(true);

            // Notify
            if (Changed()) NotifyChange();
          }
        });

        // Append
        mDropdownPanel.Append(mCalendar.Element());
      }

      // Show
      mDropdownPanel.Show(310, false); //332
      mDropdownPanel.AttachedControl(_self);

      // Focus TextBox
      if (!mIsSmallMobileBrowser) {
        mElement.focus();
        mElement.select();
      }

      // Value property may not have been originally set using the Value() method, e.g., in an HTML Widget so account for this
      if (mValue === null && mElement[0].value) {
        TextToValue(mElement[0].value);
      }

      // Sync Calendar
      mCalendar.Value(mValue);
      mCalendar.GotoValue();
    }

    // ---------------------
    // PUBLIC: Hide Dropdown
    // ---------------------
    function DropdownHide(focus) {
      mDropdownPanel.Hide();

      if (focus) {
        mElement.focus();
        mElement.select();
      }
    }

    // ---------------
    // Update the Text
    // ---------------
    function TextToValue(text) {
      // Update value from text
      if (!mOptions.readOnly) {
        if (text == "") {
          mValue = null;
        }
        else {
          // Convert value
          mValue = Runtime_ParseDate(text, mOptions.historic, !mOptions.valueIsUtc);
        }
      }

      // Update text
      UpdateText();
    }

    // ---------------
    // Update the Text
    // ---------------
    function UpdateText() {
      if (mIsDateField) {
        // Do nothing special for HTML 5 date type fields
        mElement[0].valueAsDate = mValue;
      }
      else {
        // Format
        // NOTE: Always display UTC dates since it is assumed that we are passing dates in UTC that should also be displayed in UTC format
        var s = Runtime_FormatDate(mValue, false, true);
        mElement.val(s);
      }

      // Description element
      if (mOptions.showAge && mValue) {
        mDescriptionElement.text(widget.GetAgeText(mValue));
      }
      else if (mOptions.showWeekDayName && mValue) {
        mDescriptionElement.text(widget.GetWeekDayNameFromDate(mValue));
      }
      else {
        mDescriptionElement.text("");
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------
    // PUBLIC: BlankTip property
    // -------------------------
    function BlankTip(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankTip;
      }
      else {
        // Set
        mOptions.blankTip = value;

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);        
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      // NOTE: Far easier to convert dates to String and compare than attempt JavaScript date comparisons
      var changed = (Runtime_FormatDate(mValue) != Runtime_FormatDate(mValueOriginal));

      return changed;
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      // Notify
      var e = { ChangeHandled: false, ValueOriginal: mValueOriginal };
      if (mElementTime) e.TimeValueOriginal = widget.ParseTime(mValueOriginalTime, true);
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset ValueOriginal?
      if (e.ChangeHandled) {
        mValueOriginal = mValue;
        if (mElementTime) mValueOriginalTime = mElementTime.val();
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------
    // PUBLIC: Show Age property
    // -------------------------
    function ShowAge(value) {
      if (value === undefined) {
        // Get
        return mOptions.showAge;
      }
      else {
        // Set
        if (value != mOptions.showAge) {
          mOptions.showAge = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        var d = mValue;
        if (d && mElementTime) {
          // Add time portion (UTC)
          var t = widget.ParseTime(mElementTime.val(), true);
          if (t) {
            d.setUTCHours(t.getUTCHours(), t.getUTCMinutes(), t.getUTCSeconds(), 0);
          }
          else {
            d.setUTCHours(0, 0, 0, 0);
          }
        }
        return d;
      }
      else {
        // Set
        if (typeof value == "string") {
          if (value.toUpperCase() == "NOW" || value.toUpperCase() == "TODAY") {
            var date = new Date();
            var now_utc = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
            mValue = new Date(now_utc);
          }
          else {
            // Most likely an ISO 8601 string
            mValue = Runtime_ParseJsonDate(value);
          }
        }
        else {
          mValue = value;
        }

        // Update text
        UpdateText();
        if (mElementTime) {
          mElementTime.val(widget.FormatTime(mValue, true, true));

          // Strip out time portion from mValue since this is added dynamically in the Get
          //mValue = Runtime_ParseDate(mElement.val());
          mValue = Runtime_ParseDate(mElement.val(), false, true);
        }

        // Update Original value
        mValueOriginal = mValue;
      }
    }

    // -------------------------------------------------------------------------------
    // PUBLIC: Get the value as an ISO 8601 String (useful for passing to GET methods)
    // -------------------------------------------------------------------------------
    function ValueAsISOString() {
      if (mValue) {
        return mValue.toISOString();
      }
      else {
        return "";
      }
    }

    // -------------------------
    // PUBLIC: MaxValue property
    // -------------------------
    function MaxValue(value) {
      if (value === undefined) {
        return mOptions.maxValue;
      }
      else {
        // Set
        mOptions.maxValue = value;
      }
    }

    // -------------------------
    // PUBLIC: MinValue property
    // -------------------------
    function MinValue(value) {
      if (value === undefined) {
        return mOptions.minValue;
      }
      else {
        // Set
        mOptions.minValue = value;
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("DateBox.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      mWrapperElement.hide();
      var parentWidth = mWrapperElement.parent().innerWidth();
      mWrapperElement.show();
      var width = mOptions.width;
      var maxWidth = "";

      if (fullWidth) {
        width = "100%";
      }
      else {
        //TODO:
        //if (mOptions.maxValue != null && mOptions.minValue != null) {
        //  //width = ("" + mOptions.maxValue).length;
        //  //mOptions.width = Math.min(width * 1.5, parentWidth) + "em";
        //  width = "6em";
        //}
        //else {
        //  width = "6em";
        //}
        //maxWidth = parentWidth + "px";
      }
      //mWrapperElement.css({ width: width, maxWidth: maxWidth });
      //mElement.css({ width: width, maxWidth: maxWidth });
    }

    // ------------------------
    // PUBLIC: Is control valid
    // ------------------------
    function IsValid() {
      return mIsValid ? true : false;
    }

    // ----------------------------------------------
    // PUBLIC: Validate (based on min and max values)
    // ----------------------------------------------
    function Validate() {
      // Initialise
      var valid = true;

      // Ensure value entered
      if (!mOptions.allowBlank && !Value()) {
        // Clear validation message since it only applies to max and min values
        ValidationSet(true, "", false);

        return false;
      }

      // Ensure Dates are Dates
      if (typeof mOptions.minValue == "string") {
        // Most likely an ISO 8601 string
        mOptions.minValue = Runtime_ParseJsonDate(mOptions.minValue);
      }
      if (typeof mOptions.maxValue == "string") {
        // Most likely an ISO 8601 string
        mOptions.maxValue = Runtime_ParseJsonDate(mOptions.maxValue);
      }

      // Validate?
      if (mOptions.ignoreMinMaxWhenNullValue && !Value()) {
        // Do not validate Min / Max values when option is set to not apply when value is null
      }
      else if (mOptions.minValue != null || mOptions.maxValue != null) {
        var value = Value();


        if (valid && mOptions.minValue != null && value < mOptions.minValue) valid = false;
        if (valid && mOptions.maxValue != null && value > mOptions.maxValue) valid = false;
      }
      else {
        // Nothing to validate
      }

      // Update element
      if (valid) {
        ValidationSet(true, "", false);
      }
      else {
        ValidationSet(false, "Valid range " + GetValidRangeText(), false);
      }

      return valid;
    }

    // -------------------------------------------------------------------------
    // PRIVATE: Get text detailing the valid range (for validation and tooltips)
    // -------------------------------------------------------------------------
    function GetValidRangeText() {
      var s = "";

      if (mOptions.minValue != null) {
        s += "from " + Runtime_FormatDate(mOptions.minValue);
      }
      if (mOptions.maxValue != null) {
        if (s) s += " ";
        s += "to " + Runtime_FormatDate(mOptions.maxValue);
      }

      return s;
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      mIsValid = isValid;
      if (validationText === undefined) mValidationText = ""; else mValidationText = validationText;
      if (validationTextIsHtml === undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

      // Update element
      UpdateElement();
    }

    // --------------------------------
    // PUBLIC: Set the OnChange handler
    // --------------------------------
    function OnChange(handler) {
      mOptions.onChange = handler;
    }

    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "DateBox",

      AllowBlank: AllowBlank,
      AutoReadOnly: AutoReadOnly,
      BlankTip: BlankTip,
      Caption: Caption,
      Changed: Changed,
      DropdownHide: DropdownHide,
      DropdownShow: DropdownShow,
      Element: Element,
      Focus: Focus,
      MaxValue: MaxValue,
      MinValue: MinValue,
      ReadOnly: ReadOnly,
      ShowAge: ShowAge,
      Value: Value,
      ValueAsISOString: ValueAsISOString,
      Visible: Visible,
      VisibleRow: VisibleRow,
      WidthResizeFromParent: WidthResizeFromParent,

      IsValid: IsValid,
      Validate: Validate,
      ValidationSet: ValidationSet,

      WrapperElement: function () { return mWrapperElement; },

      OnChange: OnChange
    };

    // Associate this control to HTML input element (for container validation)
    mElement.prop("is-control", _self);

    return _self;
  }

  // ==========================
  // PUBLIC: Expiry Date object
  // ==========================
  function ExpiryDate(e, options) {

    var mElement;
    var mWrapperElement;
    var mIsValid = true;
    var mMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;

    var C = {
      dateExpiryDate: null,
      cboExpiryMonth: null,
      cboExpiryYear: null,
    };

    // Extend options with defaults
    ExpiryDateDefaults = {
      blankTip: "",
      captionElement: "auto",
      cssClass: "is-expirydate",

      allowDay: true,
      allowBlank: true,
      allowDropdown: true,
      allowTime: false,

      historic: false,

      valueIsUtc: false,  // Set to true if hosting a UTC date so that it is displayed in local time, if false, the date will be formatted with the exact UTC values, i.e., not converted to local time

      maxValue: null,
      minValue: null,

      readOnly: false,
      autoReadOnly: true,

      showWeekDayName: false,
      showAge: false,

      width: "auto",
      visible: true,

      onChange: null,
    };
    var mOptions = $.extend({}, ExpiryDateDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.ExpiryDate: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);
    mWrapperElement = $(mElement.parent());

    // Validate Element
    switch (mElement.prop("tagName")) {
      case "INPUT":
        break;

      default:
        console.warn("widget_ui.ExpiryDate: Element '" + id + "' must be a INPUT element.");
        return;
    }

    // Create sub-elements and controls
    //   Expiry Date    
    //var tr = $("<tr><th><label for='" + cid + "'></label></th><td><input id='" + cid + "'/></td></tr>")
    //mElement.append(tr);

    C.dateExpiryDate = DateBox($("#" + id), {
      blankTip: mOptions.blankTip,
      captionElement: mOptions.captionElement,

      allowBlank: mOptions.allowBlank,
      allowDropdown: mOptions.allowDropdown,
      allowTime: mOptions.allowTime,

      historic: mOptions.historic,

      valueIsUtc: mOptions.valueIsUtc,

      maxValue: mOptions.maxValue,
      minValue: mOptions.minValue,

      readOnly: mOptions.readOnly,
      autoReadOnly: mOptions.autoReadOnly,

      showWeekDayName: mOptions.showWeekDayName,
      showAge: mOptions.showAge,

      width: mOptions.width,
      visible: mOptions.visible,

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        NotifyChange();
      },
    });

    var cid = CreateGuid(true);
    var span = $("<span><input id='" + cid + "'/> <input id='" + cid + "2'/> <label style='display:none; position:relative' class='is-combobox is-validation-tip'></label></span>");
    mValidationElement = $(".is-validation-tip", span);
    mWrapperElement.append(span);

    C.cboExpiryMonth = ComboBox($("#" + cid), {
      allowBlank: mOptions.allowBlank,
      limitToList: false,
      maxLength: 3,
      width: "4em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        NotifyChange();
      },
    });
    C.cboExpiryMonth.ListFromArray(mMonths);
    C.cboExpiryMonth.Element().blur(function () {
      // Allow month to be entered as a numeric value
      if (C.cboExpiryMonth.Text()) {
        var month = Runtime_ParseNumber(C.cboExpiryMonth.Text());
        if (month > 0) {
          // Convert to list value
          C.cboExpiryMonth.ListIndex(month - 1);
        }
        else {
          // Limit to list
          if (!C.cboExpiryMonth.ListExists(C.cboExpiryMonth.Text())) {
            C.cboExpiryMonth.Text("");
          }
        }
      }
    });

    C.cboExpiryYear = ComboBox($("#" + cid + "2"), {
      allowBlank: mOptions.allowBlank,
      limitToList: false,
      maxLength: 4,
      width: "5em",

      onChange: function (sender, e) {
        e.ChangeHandled = true;
        NotifyChange();
      },
    });
    C.cboExpiryYear.Element().blur(function () {
      // Allow 2-digit year entry
      if (C.cboExpiryYear.Text()) {
        var year = Runtime_ParseNumber(C.cboExpiryYear.Text());
        if (year < 100) year += 2000;
        if (year > 9999) year = 9999;
        C.cboExpiryYear.Text(year);
      }
    });
    var arrYears = [];
    var start = new Date().getFullYear(), end = start + 10;
    if (mOptions.historic) start -= 10;
    for (var i = start; i < end; i++) {
      arrYears.push(i + "");
    }
    C.cboExpiryYear.ListFromArray(arrYears);    

    // Initialise
    UpdateElement();

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      // Ensure all controls are kept in sync
      var updateValue = false;
      if (mOptions.allowDay) {
        updateValue = true;
      }
      else if (C.cboExpiryMonth.Text() && C.cboExpiryYear.Text()) {
        updateValue = true;
      }
      if (updateValue) Value(Value());

      // Notify      
      if (mOptions.onChange) mOptions.onChange(_self, e);
    }

    // --------------------------
    // PUBLIC: Allow Day property
    // --------------------------
    function AllowDay(value) {
      if (value === undefined) {
        // Get
        return mOptions.allowDay;
      }
      else {
        // Set
        if (value != mOptions.allowDay) {
          mOptions.allowDay = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------
    // PUBLIC: BlankTip property
    // -------------------------
    function BlankTip(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankTip;
      }
      else {
        // Set
        mOptions.blankTip = value;

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        return C.dateExpiryDate.Caption();
      }
      else {
        // Set
        C.dateExpiryDate.Caption(value);
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      if (mOptions.allowDay) {
        return C.dateExpiryDate.Changed();
      }
      else {
        return (C.cboExpiryMonth.Changed() || C.cboExpiryYear.Changed());
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      if (mOptions.allowDay) {
        C.dateExpiryDate.Focus();
      }
      else {
        C.cboExpiryMonth.Focus();
      }
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------
    // PUBLIC: MaxValue property
    // -------------------------
    function MaxValue(value) {
      if (value === undefined) {
        return mOptions.maxValue;
      }
      else {
        // Set
        mOptions.maxValue = value;

        // Update element
        UpdateElement();
      }
    }

    // -------------------------
    // PUBLIC: MinValue property
    // -------------------------
    function MinValue(value) {
      if (value === undefined) {
        return mOptions.minValue;
      }
      else {
        // Set
        mOptions.minValue = value;

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      if (value === undefined) {
        // Get
        if (mOptions.allowDay) {
          return C.dateExpiryDate.VisibleRow();
        }
        else {
          return C.cboExpiryMonth.VisibleRow();
        }
      }
      else {
        if (mOptions.allowDay) {
          C.dateExpiryDate.VisibleRow(value);
        }
        else {
          C.cboExpiryMonth.VisibleRow(value);
          C.cboExpiryYear.VisibleRow(value);
        }
      }
    }    

    // ------------------------
    // PUBLIC: Is control valid
    // ------------------------
    function IsValid() {
      return mIsValid ? true : false;
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        if (mOptions.allowDay) {
          return C.dateExpiryDate.Value();
        }
        else if (C.cboExpiryMonth.Text() && C.cboExpiryYear.Text()) {
          var month = C.cboExpiryMonth.ListIndex();
          if (month == -1) month = 0;

          var d = new Date(C.cboExpiryYear.Text(), month + 1, 0);
          var d_utc = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
          return new Date(d_utc);
        }
        else {
          // Return empty date
          return new Date("");
        }
      }
      else {
        // Set
        C.dateExpiryDate.Value(value);

        var d = Runtime_ParseJsonDate(value);
        if (d) {
          C.cboExpiryYear.Text(d.getFullYear());
          C.cboExpiryMonth.ListIndex(d.getMonth());
        }
        else {
          C.cboExpiryYear.Text("");
          C.cboExpiryMonth.Text("");
        }        
      }
    }

    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Allow Blank
      C.dateExpiryDate.AllowBlank(mOptions.allowBlank);
      C.cboExpiryMonth.AllowBlank(mOptions.allowBlank);
      C.cboExpiryYear.AllowBlank(mOptions.allowBlank);

      // Blank Tip
      C.dateExpiryDate.BlankTip(mOptions.blankTip);

      // Read Only
      C.dateExpiryDate.AutoReadOnly(mOptions.autoReadOnly);
      C.dateExpiryDate.ReadOnly(mOptions.readOnly);
      C.cboExpiryMonth.AutoReadOnly(mOptions.autoReadOnly);
      C.cboExpiryYear.AutoReadOnly(mOptions.autoReadOnly);
      C.cboExpiryMonth.ReadOnly(mOptions.readOnly);
      C.cboExpiryYear.ReadOnly(mOptions.readOnly);

      // Min / Max Value
      C.dateExpiryDate.MinValue(mOptions.minValue);
      C.dateExpiryDate.MaxValue(mOptions.maxValue);

      // Option specific
      if (mOptions.allowDay) {
        // Update Controls
        C.dateExpiryDate.Visible(true);
        C.cboExpiryMonth.Visible(false);
        C.cboExpiryYear.Visible(false);

        // Visible
        C.dateExpiryDate.Visible(mOptions.visible);
      }
      else {
        // Update Controls
        C.dateExpiryDate.Visible(false);
        C.cboExpiryMonth.Visible(true);
        C.cboExpiryYear.Visible(true);

        // Visible
        C.cboExpiryMonth.Visible(mOptions.visible);
        C.cboExpiryYear.Visible(mOptions.visible);

        // Validation message
        if (mIsValid) {
          mValidationElement.css({ display: "none" });
          mElement.removeClass("is-invalid");
        }
        else {
          mElement.addClass("is-invalid");
          if (mValidationText) {
            if (mValidationTextIsHtml) {
              mValidationElement.html(mValidationText);
            }
            else {
              mValidationElement.text(mValidationText);
            }
            mValidationElement.css({ display: "inline-flex" });
          }
          else {
            mValidationElement.css({ display: "none" });
          }
        }
      }
    }

    // --------------------------------
    // PUBLIC: Set the OnChange handler
    // --------------------------------
    function OnChange(handler) {
      mOptions.onChange = handler;
      if (mOptions.allowDay) {
        C.dateExpiryDate.OnChange(handler);
      }
      else {
        C.cboExpiryMonth.OnChange(handler);
        C.cboExpiryYear.OnChange(handler);
      }      
    }

    // ----------------
    // PUBLIC: Validate
    // ----------------
    function Validate() {
      if (mOptions.allowDay) {
        mIsValid = C.dateExpiryDate.Validate();
        return mIsValid;
      }
      else {
        var valid = true;

        // Custom Min / Max validation
        if (valid) {
          // Ensure Dates are Dates
          if (typeof mOptions.minValue == "string") {
            // Most likely an ISO 8601 string
            mOptions.minValue = Runtime_ParseJsonDate(mOptions.minValue);
          }
          if (typeof mOptions.maxValue == "string") {
            // Most likely an ISO 8601 string
            mOptions.maxValue = Runtime_ParseJsonDate(mOptions.maxValue);
          }

          // Validate?
          if (mOptions.minValue != null || mOptions.maxValue != null) {
            var value = Value();


            if (valid && mOptions.minValue != null && value < mOptions.minValue) valid = false;
            if (valid && mOptions.maxValue != null && value > mOptions.maxValue) valid = false;
          }
          else {
            // Nothing to validate
          }

          // Update element
          if (valid) {
            ValidationSet(true, "", false);
          }
          else {
            ValidationSet(false, "Valid range " + GetValidRangeText(), false);
          }
        }

        return valid;
      }
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      if (mOptions.allowDay) {
        C.dateExpiryDate.ValidationSet(isValid, validationText, validationTextIsHtml);
      }
      else {
        mIsValid = isValid;
        if (validationText === undefined) mValidationText = ""; else mValidationText = validationText;
        if (validationTextIsHtml === undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

        // Update element
        UpdateElement();
      }
    }

    // ------------------------------------------------------------
    // PRIVATE: Get text detailing the valid range (for validation)
    // ------------------------------------------------------------
    function GetValidRangeText() {
      var s = "";

      if (mOptions.minValue != null) {
        s += "from " + FormatDateMonthYear(mOptions.minValue);
      }
      if (mOptions.maxValue != null) {
        if (s) s += " ";
        s += "to " + FormatDateMonthYear(mOptions.maxValue);
      }

      return s;
    }

    // =======================================
    // PRIVATE: Format Value as Month and Year
    // =======================================
    function FormatDateMonthYear(date) {
      var s = "";

      // Format
      s += mMonths[date.getMonth()];
      s += " ";
      s += date.getFullYear();

      return s;
    }

    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "ExpiryDate",

      AllowBlank: AllowBlank,
      AllowDay: AllowDay,
      AutoReadOnly: AutoReadOnly,
      BlankTip: BlankTip,
      Caption: Caption,
      Changed: Changed,      
      Element: Element,
      Focus: Focus,
      MaxValue: MaxValue,
      MinValue: MinValue,
      ReadOnly: ReadOnly,
      Value: Value,
      Visible: Visible,
      VisibleRow: VisibleRow,

      IsValid: IsValid,
      Validate: Validate,
      ValidationSet: ValidationSet,

      WrapperElement: function () { return mWrapperElement; },

      OnChange: OnChange
    };

    // Associate this control to HTML input element (for container validation)
    mElement.prop("is-control", _self);

    return _self;
  }

  // ======================
  // PUBLIC: TimeBox object
  // ======================
  function TimeBox(e, options) {

    var mButtonElement;
    var mDropdownPanel;
    var mElement;
    var mHasFocus = false;
    var mIsTimeField = false; // Is this a true HTML 5 time type field?
    var mIsValid = true;
    var mLabelElement;
    var mList = [];
    var mListElement;
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;
    var mValue = null;
    var mValueOriginal = null;
    var mWrapperElement;

    // Extend options with defaults
    TimeBoxDefaults = {
      captionElement: "auto",
      cssClass: "is-timebox",

      allowBlank: true,

      historic: false,

      valueIsUtc: false,  // Set to true if hosting a UTC date so that it is displayed in local time, if false, the time will be formatted with the exact UTC values, i.e., not converted to local time

      maxValue: null,
      minValue: null,

      readOnly: false,
      autoReadOnly: true,

      width: "auto",
      visible: true,

      onChange: null,

      usePicker: window.__alwaysUsePickerControls,
      pickerCaption: ""
    };
    var mOptions = $.extend({}, TimeBoxDefaults, options);

    // Force Picker Use
    //if ($UI.AlwaysUsePickerControls()) mOptions.usePicker = true;

    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.TimeBox: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Replace Element since we (in some circumstances) want to use a proper 'time' type input element but some browsers don't let you change this on the fly
    // NOTE: Mobile time fields don't support seconds so don't use for now
    //if ($Runtime.IsMobileBrowser()) {
    //  mIsTimeField = true;
    //  mElement.replaceWith("<input type='time' id='" + id + "' class='native'/>");
    //  mElement = $($("#" + id)[0]);
    //}

    // Wrap element
    //mElement.wrap("<span style='white-space:normal; display:inline-block; padding:0; margin:0;'/>");
    //mElement.wrap("<span style='display:inline-block; padding:0; position:relative; margin:0' controlType='timebox'/>");
    mElement.wrap("<span style='white-space:nowrap; display:inline-flex; flex-direction:row' controltype='timebox'/>");
    mWrapperElement = $(mElement.parent());

    // Dropdown button
    // FUDGE: No idea why but when button is positioned relative, it seems to add margins that mess up layout
    //mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button' style='position:absolute; right:0'/>");
    mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button' style='position:relative;left:1px;top:0'/>");
    if (mOptions.usePicker) {
      mButtonElement.addClass("is-picker");
    }
    mWrapperElement.append(mButtonElement);
    //if ($UI.AlwaysUsePickerControls()) mButtonElement.addClass("always-use-pickers"); // More for when widgets hook in

    // Dropdown panel
    mDropdownPanel = new DropdownPanel(mWrapperElement, { minWidthElement: mElement });

    // Turn auto-complete and spellcheck off since it interferes with our functionality
    mElement.attr("autocomplete", "off");
    mElement.attr("spellcheck", "false");

    // Validation elements
    mValidationElement = $("<label style='display:none' class='is-validation-tip'></label>");
    mWrapperElement.append(mValidationElement);

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Initialise
    UpdateElement();

    // Calculate width if 'auto'
    if (mOptions.width == "auto") {
      WidthResizeFromParent();
    }

    // Handle events to format/ unformat values and fire OnChange event
    if (mIsTimeField) {
      mElement.blur(function () {
        // Initialise
        mHasFocus = false;

        // Format
        //UpdateText();
      });
      mElement.focus(function () {
        // Initialise
        mHasFocus = true;

        // Unformat for editing
        // Not allowed for HTML 5 date type fields
      });
    }
    else {
      mElement.blur(function () {
        // Initialise
        mHasFocus = false;

        // Parse
        //UpdateText();
      });
      mElement.focus(function () {
        // Initialise
        mHasFocus = true;
      });
    }
    mElement.blur(function () {
      if (!mOptions.readOnly) {
        if (mIsTimeField) {
          mValue = mElement[0].valueAsDate;
        }
        else {
          TextToValue(mElement.val());
        }
      }
      if (Changed()) {
        NotifyChange();
      }
      mValueOriginal = mValue;

      // Format
      UpdateText();
    });

    mButtonElement.bind("click", function () {
      if (!mOptions.readOnly) {
        if (mDropdownPanel.Visible())
          DropdownHide(true);
        else
          DropdownShow();
      }
    });


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // Allow Blank
      if (mOptions.allowBlank) {
        mElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
        mButtonElement.hide();
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("readonly");
        mButtonElement.show();
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Other
      mElement.attr("maxLength", mOptions.maxLength == 0 ? "" : mOptions.maxLength);
      if (mOptions.width != "auto") mElement.css({ width: mOptions.width });
      mElement.attr("spellcheck", "false");

      // Validation message
      if (mIsValid) {
        mValidationElement.css({ display: "none" });
        mElement.removeClass("is-invalid");
      }
      else {
        mElement.addClass("is-invalid");
        if (mValidationText) {
          if (mValidationTextIsHtml) {
            mValidationElement.html(mValidationText);
          }
          else {
            mValidationElement.text(mValidationText);
          }
          mValidationElement.css({ display: "flex" });
        }
        else {
          mValidationElement.css({ display: "none" });
        }
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }

      //// Time field specific
      //if (mIsTimeField) {
      //}
    }

    // -------------
    // Show Dropdown
    // -------------
    function DropdownShow() {
      // Update List
      if (!mListElement) {
        // Create List
        var options = "<ul>";
        if (mOptions.usePicker) {
          options += "<li class='is-selectable' style='text-align:right; font-weight:bold' h='*' m='0'>Current&nbsp;Time</li>";
        }
        else {
          options += "<li class='is-selectable' style='text-align:right; font-weight:bold' h='*' m='0'>Current</li>";
        }
        for (var i = 0; i < 24; i++) {
          var s1 = "", s2 = "";
          if (i < 13) {
            s1 = i;
            s2 = i;
          }
          else {
            s1 = i - 12;
            s2 = i - 12;
          }
          s1 += ":00 ";
          s2 += ":30 ";
          if (i >= 12) {
            s1 += " p.m.";
            s2 += " p.m.";
          }
          else {
            s1 += " a.m.";
            s2 += " a.m.";
          }
          options += "<li class='is-selectable' style='text-align:right' h='" + i + "' m='0'>" + s1 + "</li>";
          options += "<li class='is-selectable' style='text-align:right' h='" + i + "' m='30'>" + s2 + "</li>";
        }
        options += "</ul>";
        mListElement = $(options);

        // Handle events
        $("li", mListElement).bind("click", function () {
          // Get time
          var h = $(this).attr("h");
          var m = $(this).attr("m");
          if (h == "*") {
            var now = new Date();
            //Value(new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()));
            Value(new Date(Date.UTC(2000, 1, 1, parseInt(now.getHours()), parseInt(now.getMinutes()), 0, 0)));
          }
          else {
            Value(new Date(Date.UTC(2000, 1, 1, parseInt(h), parseInt(m), 0, 0)));
          }

          if (!mOptions.usePicker) DropdownHide(true);
          NotifyChange(true);
          if (mOptions.usePicker) {
            $UI.SharedPickerPanel().Hide(true);
          }
        });

        // Append
        if (!mOptions.usePicker) mDropdownPanel.Append(mListElement);
      }

      // Show
      if (mOptions.usePicker) {
        // ------------
        // Picker Panel
        // ------------
        // Get Caption
        var caption = mOptions.pickerCaption;
        if (!caption && mLabelElement) {
          caption = mLabelElement.text();
          if (caption) {
            caption = "Select " + caption;
            if (caption.endsWith(":")) caption = caption.substr(0, caption.length - 1);

          }
        }
        if (!caption) caption = "Select Time";

        // Show Picker Panel
        SharedPickerPanel().Toggle({
          closeFocusElement: _self,
          sourceButtonElement: mButtonElement,
          caption: caption,
          contentElement: mListElement,
          context: "calendar",
        });
      }
      else {
        // -------------
        // Dropdown List
        // -------------
        mDropdownPanel.Show();
        mDropdownPanel.AttachedControl(_self);

        // Focus TextBox
        if (!mIsSmallMobileBrowser) {
          mElement.focus();
          mElement.select();
        }
      }
    }

    // -------------
    // Hide Dropdown
    // -------------
    function DropdownHide(focus) {
      if (mOptions.usePicker) {
        SharedPickerPanel().Hide();
      }
      else {
        mDropdownPanel.Hide();

        if (focus) {
          mElement.focus();
          mElement.select();
        }
      }
    }

    // ---------------
    // Update the Text
    // ---------------
    function TextToValue(text) {
      // Update value from text
      if (!mOptions.readOnly) {
        if (text == "") {
          mValue = null;
        }
        else {
          // Convert value
          mValue = widget.ParseTime(text, true);
        }
      }

      // Update text
      UpdateText();
    }

    // ---------------
    // Update the Text
    // ---------------
    function UpdateText() {
      if (mIsTimeField) {
        // Do nothing special for HTML 5 date type fields
        mElement[0].valueAsDate = mValue;
      }
      else {
        // Format (blank if midnight)
        mElement.val(widget.FormatTime(mValue, true, true));
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value == undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return !(mValue == mValueOriginal);
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      // Notify
      var e = { ChangeHandled: false, ValueOriginal: mValueOriginal };
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset TextOriginal?
      if (e.ChangeHandled) mTextOriginal = mElement.val();
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // ----------------------------
    // PUBLIC: Read-Only property
    // ----------------------------
    function ReadOnly(value) {
      if (value == undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value == undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        return mValue;
      }
      else {
        // Set
        if (typeof value === "string") {
          // Most likely an ISO 8601 string
          mValue = Runtime_ParseJsonDate(value);
        }
        else {
          mValue = value;
        }

        // Update text
        UpdateText();
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value == undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      mWrapperElement.hide();
      var parentWidth = mWrapperElement.parent().innerWidth();
      mWrapperElement.show();
      var width = mOptions.width;
      var maxWidth = "";

      if (fullWidth) {
        width = "100%";
      }
      else {
        //TODO:
        //if (mOptions.maxValue != null && mOptions.minValue != null) {
        //  //width = ("" + mOptions.maxValue).length;
        //  //mOptions.width = Math.min(width * 1.5, parentWidth) + "em";
        //  width = "6em";
        //}
        //else {
        //  width = "6em";
        //}
        //maxWidth = parentWidth + "px";
      }
      //mWrapperElement.css({ width: width, maxWidth: maxWidth });
      //mElement.css({ width: width, maxWidth: maxWidth });
    }

    // ------------------------
    // PUBLIC: Is control valid
    // ------------------------
    function IsValid() {
      return mIsValid ? true : false;
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      mIsValid = isValid;
      if (validationText == undefined) mValidationText = ""; else mValidationText = validationText;
      if (validationTextIsHtml == undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

      // Update element
      UpdateElement();
    }

    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "TimeBox",

      AllowBlank: AllowBlank,
      AutoReadOnly: AutoReadOnly,
      Caption: Caption,
      Changed: Changed,
      Element: Element,
      Focus: Focus,
      ReadOnly: ReadOnly,
      Value: Value,
      Visible: Visible,
      WidthResizeFromParent: WidthResizeFromParent,

      IsValid: IsValid,
      ValidationSet: ValidationSet,

      /* Friend (internal use only) */
      WrapperElement: function () { return mWrapperElement; },
    };
    return _self;
  }


  // ===========================
  // PUBLIC: DateTimeZone object
  // ===========================
  function DateTimeZone(e, options) {

    // Use finPOWER Connect Cloud DateTimeZone (to respect picker panel etc)
    if (!mDisableProxyControls && !mDisableControlStyling && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      if (typeof e == "string") {
        e = $("#" + e);
      }
      e.attr("is-created", "y");
      options.widgetDocument = window.document;
      var d = new window.parent.$UI.DateTimeZone(e, options);
      return d;
    }

    var mDateBox;
    var mElement;
    var mElementRow;
    var mHasFocus = false;
    var mIsValid = true;
    var mLabelElement;
    var mTimeBox;
    var mTimeZoneCombo;
    var mTimeZoneVisible = false;
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;
    var mValue = null;
    var mValueOriginal = null;
    var mWrapperElement;

    // Extend options with defaults
    DateTimeZoneDefaults = {
      allowBlank: true,

      historic: false,

      maxValue: null,
      minValue: null,

      readOnly: false,
      autoReadOnly: true,

      visible: true,
      timeZoneVisible: true,
      timeVisible: true,

      onChange: null
    };
    var mOptions = $.extend({}, DateTimeZoneDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.DateTimeZone: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Wrap element
    // NOTE: No need since the element itself should be a div and becomes the wrapper
    mWrapperElement = mElement;
    mWrapperElement.css("margin", "0");
    mWrapperElement.css("padding", "0");

    // Use a Table to prevent control resize issues, particularly on mobile
    var eTable = $("<table class='is-datetimezone' style='width:100%'><tr><td style='width:1px'><input class='d'/></td><td style='width:1px'><input class='t'/><td><input class='tz'/></td></td></tr></table>");
    mWrapperElement.append(eTable);

    // Add necessary controls
    var eDate = $("input.d", eTable);
    var eTime = $("input.t", eTable);
    var eCombo = $("input.tz", eTable);
    mDateBox = DateBox(eDate, {
      onChange: NotifyChange,
    });
    mTimeBox = TimeBox(eTime, {
      //valueIsUtc: true,
      onChange: NotifyChange,
    });
    mTimeBox.WrapperElement().css("margin-right", "4px");
    mTimeBox.WrapperElement().css("margin-left", "4px");
    mTimeZoneCombo = ComboBox(eCombo, {
      blankTip: _config.defaultTimeZoneDescription,
      limitToList: true,
      pickerCaption: "Select Time Zone",
      maxLength: 255,

      onChange: NotifyChange,
    });

    // Set Time Zone list
    if (!_config.timeZones.ArrayAllowLookupById) {
      widget.ArrayAllowLookupById(_config.timeZones, "Code");
    }
    mTimeZoneCombo.ListFromCodeDescriptionList(_config.timeZones);

    // Validation elements
    mValidationElement = $("<label style='display:none' class='is-validation-tip'></label>");
    mWrapperElement.append(mValidationElement);

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));
    if (mLabelElement) {
      mLabelElement.click(function () {
        mDateBox.Focus();
      });
    }

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      //if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // Allow Blank
      if (mOptions.allowBlank) {
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }
      mDateBox.AllowBlank(mOptions.allowBlank);
      mTimeBox.AllowBlank(true);

      // Read-only
      mDateBox.ReadOnly(mOptions.readOnly);
      mDateBox.AutoReadOnly(mOptions.autoReadOnly);
      mTimeBox.ReadOnly(mOptions.readOnly);
      mTimeBox.AutoReadOnly(mOptions.autoReadOnly);
      mTimeZoneCombo.ReadOnly(mOptions.readOnly);
      mTimeZoneCombo.AutoReadOnly(mOptions.autoReadOnly);

      // Time
      mTimeBox.Visible(mOptions.timeVisible);

      // Time Zone
      if (!mOptions.timeZoneVisible) {
        // Never show, e.g., Log Action Complete date
        mTimeZoneCombo.Visible(false);
        mTimeZoneVisible = false;
      }
      else if (!_config.timeZoneUse) {
        // Not using Time Zones but must still show if not using the database Time Zone
        var timeZoneId = TimeZoneId();
        if (timeZoneId && _config.defaultTimeZoneId == timeZoneId) {
          // Default Time Zone so hide
          mTimeZoneCombo.Visible(false);
          mTimeZoneVisible = false;
        }
        else if (!timeZoneId) {
          // No Time Zone set so hide
          mTimeZoneCombo.Visible(false);
          mTimeZoneVisible = false;
        }
        else {
          // Must show Time Zone, regardless since it does not match the database Time Zone
          mTimeZoneCombo.Visible(true);
          mTimeZoneVisible = true;
        }
      }
      else {
        mTimeZoneCombo.Visible(true);
        mTimeZoneVisible = true;
      }
      mTimeZoneCombo.WrapperElement().css("max-width", "360px");

      // Other

      // Validation message
      if (mIsValid) {
        mValidationElement.css({ display: "none" });
        mElement.removeClass("is-invalid");
      }
      else {
        mElement.addClass("is-invalid");
        if (mValidationText) {
          if (mValidationTextIsHtml) {
            mValidationElement.html(mValidationText);
          }
          else {
            mValidationElement.text(mValidationText);
          }
          mValidationElement.css({ display: "flex" });
        }
        else {
          mValidationElement.css({ display: "none" });
        }
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value == undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return !(mValue == mValueOriginal);
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange(source, e) {
      // Always assume change handled in source
      if (e) e.ChangeHandled = true;

      // Notify
      var e2 = { ChangeHandled: false, ValueOriginal: mValueOriginal };
      if (mOptions.onChange) mOptions.onChange(_self, e2);

      // Reset TextOriginal?
      if (e.ChangeHandled) mTextOriginal = mElement.val();
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mDateBox.Focus();
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value == undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value == undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ---------------------------
    // PUBLIC: TimeZoneId property
    // ---------------------------
    function TimeZoneId(value) {
      if (value == undefined) {
        // Get
        // Lookup Time Zone Id
        var s = mTimeZoneCombo.Text().toUpperCase();
        for (var i = 0; i < _config.timeZones.length; i++) {
          var item = _config.timeZones[i];
          if (item.Description.toUpperCase() == s) {
            return item.Code;
          }
        }
        
        return null;
      }
      else {
        // Set
        if (value) {
          // Lookup Time Zone Description
          for (var i = 0; i < _config.timeZones.length; i++) {
            var item = _config.timeZones[i];
            if (item.Code == value) {
              mTimeZoneCombo.Text(item.Description);
            }
          }
        }
        else {
          mTimeZoneCombo.Text("");
        }

        // Update element (Time Zone dropdown may be shown/ hidden if not using Time Zones)
        UpdateElement();
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        if (mOptions.timeVisible) {
          // Date and Time
          return Runtime_CombineDateTimeUtc(mDateBox.Value(), mTimeBox.Value());
        }
        else {
          // Date only
          //return $Runtime.GetDateUtc(mDateBox.Value());
          return mDateBox.Value();
        }
      }
      else {
        // Set
        if (typeof value === "string") {
          // Most likely an ISO 8601 string
          value = Runtime_ParseJsonDate(value);
        }

        // Update Values        
        mDateBox.Value(value);
        mTimeBox.Value(value);
      }
    }

    // ----------------------------------------------
    // PUBLIC: Set Value to the current Date and Time
    // ----------------------------------------------
    function ValueSetNow() {
      mDateBox.Value("now");
      mTimeBox.Value(widget.ParseTime("now", true));
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value == undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("DateTimeZone.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // ------------------------
    // PUBLIC: Is control valid
    // ------------------------
    function IsValid() {
      return mIsValid ? true : false;
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      mIsValid = isValid;
      if (validationText == undefined) mValidationText = ""; else mValidationText = validationText;
      if (validationTextIsHtml == undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

      // Update element
      UpdateElement();
    }

    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "DateTimeZone",

      AllowBlank: AllowBlank,
      AutoReadOnly: AutoReadOnly,
      Caption: Caption,
      Changed: Changed,
      Element: Element,
      Focus: Focus,
      ReadOnly: ReadOnly,
      TimeZoneId: TimeZoneId,
      Value: Value,
      ValueSetNow: ValueSetNow,
      Visible: Visible,
      VisibleRow: VisibleRow,

      IsValid: IsValid,
      ValidationSet: ValidationSet
    };
    return _self;
  }


  // ===================================
  // PUBLIC: Date Cycle Combo Box object
  // ===================================
  function DateCycleComboBox(e, options) {

    // Use finPOWER Connect Cloud DateCycleComboBox (to respect picker panel etc)
    if (!mDisableProxyControls && !mDisableControlStyling && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      if (typeof e == "string") {
        e = $("#" + e);
      }
      e.attr("is-created", "y");
      options.widgetDocument = window.document;
      var c = window.parent.$UI.DateCycleComboBox(e, options);
      return c;
    }


    var mComboBox;
    var mDescription = null;
    var mOptions = options;
    var mTextOriginal = "";
    var mSuppliedOnChange = null;

    // Forced options/ defaults (some of these are just initialisation values that will be set later)
    options.showColumnHeadings = false;
    if (options.showDescription == false) options.showDescription = false; else options.showDecription = true;
    options.maxLength = 20;
    options.isFrequency = options.isFrequency ? true : false;
    if (options.width === undefined) options.width = "12em";
    if (options.list === undefined) options.list = "";
    if (options.listOther === undefined) options.listOther = "";
    mSuppliedOnChange = options.onChange;
    options.onChange = function (sender, e) {
      // Update Description
      UpdateDescription();

      // Notify
      if (mSuppliedOnChange) {
        mSuppliedOnChange(sender, e);
      }
      else {
        if (e) e.ChangeHandled = true;
      }
      mTextOriginal = mComboBox.Text();
    }

    // Create ComboBox (always use a DBCombo)
    mComboBox = widget.UI.DBCombo(e, options);
    mComboBox.WidthResizeFromParent();
    mComboBox.ListFromCsvString("");

    // Initialise
    //RebuildList();


    // ---------------------
    // PRIVATE: Rebuild List
    // ---------------------
    function RebuildList() {
      // NOTE: options.listOther is for validation purposes only (not yet implemented)
      mComboBox.ListFromCsvString(options.list);
    }

    // -----------------------------------------------------
    // PRIVATE: Check if a value appears in the 'Other' List
    // -----------------------------------------------------
    function ListOtherExists(s) {
      if (mOptions.listOther && s) {
        var arr = mOptions.listOther.split(",");
        s = s.toUpperCase();
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].toUpperCase() == s) return true;
        }
      }

      return false;
    }

    // ---------------------------
    // PRIVATE: Update Description
    // ---------------------------
    function UpdateDescription() {
      var text = mComboBox.Text();

      if (!text) {
        mComboBox.DescriptionUpdate("");
      }
      else if (mTextOriginal == text) {
        // Unchanged
      }
      else if (ListOtherExists(text)) {
        // In 'Other' List which means it is a special value that shouldn't fetch a description
        mComboBox.DescriptionUpdate("");
      }
      else {
        // Clear
        mComboBox.DescriptionUpdate("");

        // Fetch
        widget._SystemGetString("GetDateCycleDescription", { dateCycle: text, isFrequency: mOptions.isFrequency },
          function (data) {
            // Split out description and friendly mnemonic
            if (data) {
              var n = data.indexOf("|");
              var description = data;
              var friendlyMnemonic = "";
              if (n != -1) {
                friendlyMnemonic = description.substr(n + 1);
                description = description.substr(0, n);
                if (description.toUpperCase() == friendlyMnemonic.toUpperCase()) description = "";
              }
              mComboBox.DescriptionUpdate(description);
              if (friendlyMnemonic) {
                mComboBox.Text(friendlyMnemonic);
                mTextOriginal = friendlyMnemonic;
              }
            }
            else {
              // No description indicates invalid cycle (unless it exists in list or listOther)
              if (mComboBox.ListIndex() != -1) {
                mComboBox.DescriptionUpdate("");
              }
              else if (options.listOther) {
                var lo = ArrayFromCsvString(options.listOther);
                var found = false;
                var text = Text().toUpperCase();
                for (var i = 0; i < lo.length; i++) {
                  if (text == lo[i].toUpperCase()) {
                    found = true;
                    break;
                  }
                }
                if (found) {
                  mComboBox.DescriptionUpdate("");
                }
                else {
                  mComboBox.DescriptionUpdate("Invalid", false, true);
                }
              }
              else {
                mComboBox.DescriptionUpdate("Invalid", false, true);
              }
            }
          },

          function (data) {
            widget.RegisterError("widget_ui.DateCycleComboBox: Failed to retrieve Date Cycle Description: " + data);
          });
      }
    }

    // ----------------------------------
    // PUBLIC: Set List from a CSV String
    // ----------------------------------
    function ListFromCsvString(value) {
      mOptions.list = value;
      RebuildList();
    }

    // ---------------------------------------
    // PUBLIC: Set ListOther from a CSV String
    // ---------------------------------------
    function ListOtherFromCsvString(value) {
      mOptions.listOther = value;
      RebuildList();
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return mComboBox.Text();
      }
      else {
        // Set
        if (value != mTextOriginal) {
          mComboBox.Text(value);

          // Update description
          UpdateDescription();
        }

        mTextOriginal = value;
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "DateCycleComboBox",

      ListFromCsvString: ListFromCsvString,
      ListOtherFromCsvString: ListOtherFromCsvString,

      /* From DBCombo */
      AllowBlank: mComboBox.AllowBlank,
      AutoReadOnly: mComboBox.AutoReadOnly,
      BlankTip: mComboBox.BlankTip,
      Caption: mComboBox.Caption,
      Element: mComboBox.Element,
      Focus: mComboBox.Focus,
      LimitToList: mComboBox.LimitToList,
      ReadOnly: mComboBox.ReadOnly,
      Text: Text,
      Visible: mComboBox.Visible,
      VisibleRow: mComboBox.VisibleRow,
      WidthResizeFromParent: mComboBox.WidthResizeFromParent,
    };

    return _self;
  }


  // ======================
  // PUBLIC: DBCombo object
  // ======================
  function DBCombo(e, options) {

    // Use finPOWER Connect Cloud DBCombo (to respect picker panel etc)
    // NOTE: A special 'forceWidgetControl' is used to ensure grids always create a Widget Control, just in case things get incompatible with finCC in the future
    if (!mDisableProxyControls && !mDisableControlStyling && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI && !(options && options.forceWidgetControl)) {
      if (typeof e == "string") {
        e = $("#" + e);
      }
      e.attr("is-created", "y");
      options.widgetDocument = window.document;
      var d = window.parent.$UI.DBCombo(e, options);
      return d;
    }


    var mArrayDescription = "";
    var mArrayDescriptionInvalid = false;
    var mButtonElement;
    var mColumnHeaderCode = "";
    var mColumnHeaderDescription = "";
    var mDataSource;
    var mDataSourceFormat = "";
    var mDataSourceIdColumn = "";
    var mDataSourceDescriptionColumn = "";
    var mDataSourceDisplayColumns = "";
    var mDescriptionElement;
    var mDropdownPanel;
    var mDropdownShowing = false;
    var mElement;
    var mElementRow;
    var mFetchingData = false;
    var mFilterBoxElement;
    var mFilterBoxInterval;
    var mFilterText = "";
    var mFilteredOutCount = 0;
    var mInternalHoldChangeEvent = 0;
    var mIsSelectElement;
    var mLabelElement;
    var mList = [];
    var mListFilteredOutIndexes = [];
    var mListDescription = [];
    var mListDirty = false;
    var mListElement;
    var mOpenFormElement;
    var mOptions;
    var mTextOriginal = "";
    var mWrapperElement;

    var mQuickSearchResults = null;
    var mQuickSearchResultsGrid = null;
    var mQuickSearchResultsTextBox = null;
    var mSpecialStandardRangeName = "";
    var mSpecialStandardRangeSqlWhere = "";
    var mQuickSearchResultsDescription = "";
    var mQuickSearchResultsDescriptionFromId = "";
    var mQuickSearchResultsDescriptionTimer = null;


    // Extend options with defaults
    ComboBoxDefaults = {
      blankTip: "",
      blankTipDescription: "",
      captionElement: "auto",
      cssClass: "is-combobox",
      descriptionElement: "auto",

      allowBlank: true,
      limitToList: false,

      maxLength: 10,

      readOnly: false,
      visible: true,

      showColumnHeadings: true,
      showDescription: true,
      autoReadOnly: true,

      showDropdown: true,
      forceDropdown: false, // For special ranges such as Accounts and Clients

      formKeyOpen: "",

      width: "auto",

      onChange: null,

      hyperlinkContent: false,
      onContentHyperlink: null,

      usePicker: false,
      pickerCaption: ""
    };
    mOptions = $.extend({}, ComboBoxDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.DBCombo: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Flag as created
    mElement.attr("is-created", "y");

    // Wrap element
    mElement.wrap("<span style='white-space:nowrap; display:flex; flex-direction:row' controltype='dbcombo'/>");
    mWrapperElement = $(mElement.parent());

    // Dropdown button
    mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button'/>");
    if (mOptions.usePicker) {
      mButtonElement.addClass("is-picker");
    }
    mButtonElement.insertAfter(mElement);

    // Description element
    if (typeof mOptions.descriptionElement == "string") {
      switch (mOptions.descriptionElement) {
        case "":
        case "none":
          break;

        case "auto":
          mDescriptionElement = $("<label class='is-combobox' style='display:none'></label>");
          mDescriptionElement.insertAfter(mButtonElement);
          break;

        default:
          console.warn("userinterface.DBCombo: options.descriptionElement must be a jQuery element or one of the following: '', 'none', 'auto'.");
          break;
      }
    }
    else {
      mDescriptionElement = mOptions.descriptionElement;
    }

    // Add 'Open Form' button?
    if (mOptions.formKeyOpen) {
      mOpenFormElement = $("<div class='is-button-strip' style='margin:0 !important'><ul><li title='Open'><a><img src='" + widget.GetIconUrl("Form_Open") + "'/></a></li></ul></div>");
      mOpenFormElement.insertAfter(mButtonElement);
      mOpenFormElement.click(function () {
        widget.ExecuteApplicationShortcutUrl("app://formshow?form=" + mOptions.formKeyOpen + "&id=" + encodeURIComponent(Text()));
      });
    }

    // Dropdown panel
    if (mOptions.showColumnHeadings) {
      mDropdownPanel = new DropdownPanel(mWrapperElement, { attachedControl: _self, createdForGrid: mOptions.createdForGrid });
    }
    else {
      // Not showing column headings so don't size less than parent control
      mDropdownPanel = new DropdownPanel(mWrapperElement, { minWidthElement: mElement, createdForGrid: mOptions.createdForGrid });
    }

    // Turn auto-complete and spellcheck off since it interferes with our functionality
    mElement.attr("autocomplete", "off");
    mElement.attr("spellcheck", "false");

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Calculate width if 'auto'
    if (mOptions.width == "auto" && mOptions.maxLength != 0) {
      WidthResizeFromParent();
    }

    // Initialise
    UpdateElement();

    // Handle events
    mElement.bind("keydown", function (e) {
      switch (e.keyCode) {
        case 13: // Enter
          if (mElement.prop("tagName") == "TEXTAREA") {
            // Text Areas are used for grid entry to allow large text strings to wrap but should not allow the enter key
            return false;
          }
          break;

        case 27: // Escape
          if (mDropdownPanel.Visible()) DropdownHide(false);
          break;

        case 38: // Cursor Up
          if (mDropdownPanel.Visible()) {
            ListIndexChange(-1, true);
            UpdateListSelectedItem();
          }

          // Allow movement in grid
          // NOTE: N/A in the finCC implementation
          if (mOptions.createdForGrid && mDropdownShowing) {
            if (e.preventPropogation) e.preventPropogation();
            return false;
          }
          break;

        case 40: // Cursor Down
          if (mDropdownPanel.Visible()) {
            ListIndexChange(1, true);
            UpdateListSelectedItem();
          }
          else if (!mOptions.readOnly) {
            DropdownShow();
          }

          // Allow movement in grid
          // NOTE: N/A in the finCC implementation
          if (mOptions.createdForGrid && mDropdownShowing) {
            if (e.preventPropogation) e.preventPropogation();
            return false;
          }
          break;
      }

      // Update description
      if (!mSpecialStandardRangeName) {
        UpdateDescription();
      }
    });
    mElement.bind("blur", function (e) {
      // Update Description on blur for special Standard Ranges such as Accounts and Clients
      if (mSpecialStandardRangeName) {
        UpdateDescription();
      }
    });

    mElement.bind("keyup", function (e) {
      var moveX = 0;

      switch (e.keyCode) {
        case 13: // Enter
          if (mDropdownPanel.Visible()) DropdownHide(true);

          // Prevent enter key from propagating, e.g., re-showing the dropdown when displayed in a grid
          e.stopPropagation();

          return false; // Prevent default key action

        case 46: // Delete
          if (mOptions.readOnly) {
            // Read-Only?
            return false;
          }
          else if (mOptions.limitToList) {
            // Value will be cleared later
          }
          else {
            moveX = -1;
          }
          break;

        case 8: // Backspace
          if (mOptions.readOnly) {
            // Read-Only?
            return false;
          }
          else {
            moveX = -1;
          }
          break;

        default:
          if (e.keyCode < 48) return;
          break;
      }

      mElement.bind("blur", function (e) {
        if (!mOptions.readOnly) {
          if (Changed()) {
            NotifyChange(false);
          }
        }
      });

      if (mSpecialStandardRangeName) {
        // Not applicable to special standard ranges
      }
      else {
        // Get list index
        var index = GetMatchIndex(mElement.val(), false);

        // Highlight selected item
        if (mDropdownPanel.Visible()) UpdateListSelectedItem();

        // Partial match?
        if (index == -1 && mOptions.limitToList && e.keyCode == 46) {
          // Clear if Delete pressed, no match and limit to list
          TextSet("", false, false);
          NotifyChange(false);
        }
        else if (index == -1) {
          // Adjust cursor pos
          var x = mElement[0].selectionStart + moveX;
          if (x < 0) x = 0;

          // Partial match
          index = GetMatchIndex(mElement.val(), true);
          if (index != -1) {
            // Highlight matched portion
            mElement.val(mList[index]);
            mElement[0].selectionStart = x;
            mElement[0].selectionEnd = 1000;
            NotifyChange(false);
          }
          else if (mOptions.limitToList) {
            // Not in list so clear (not for DBCombo since the list may not be loaded)
            //TextSet("", false, false);
          }
        }

        // Update description
        UpdateDescription();
      }
    });

    if (mOptions.onContentHyperlink) {
      mElement.on("click", function () {
        if (mOptions.readOnly && mOptions.hyperlinkContent && mOptions.onContentHyperlink) {
          mOptions.onContentHyperlink();
        }
      });
    }

    mButtonElement.bind("click", function () {
      if (!mOptions.readOnly && !mFetchingData) {
        if (mDropdownPanel.Visible())
          DropdownHide(true);
        else
          DropdownShow();
      }
    });

    // Enter key moves to next field (finPOWER Connect desktop only)?
    if (widget.Options.enterMovesToNextField) {
      mElement.on("keyup", function (e) {
        if (e.keyCode == 13) TriggerTab($(this));
      });
    }


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // Allow Blank
      if (mOptions.allowBlank) {
        mElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }
      if (mDisableControlStyling) {
        // Setting blank tip to blank affects: Material Design Lite
        if (mOptions.blankTip) mElement.attr("placeholder", mOptions.blankTip);
      }
      else {
        mElement.attr("placeholder", mOptions.blankTip);
      }

      // Read-only
      if (mFetchingData) {
        // Fetching Data
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
        mElement.addClass("fetchingdata");
        mButtonElement.addClass("fetchingdata");
      }
      else if (mOptions.readOnly) {
        // Read-Only
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
        mElement.removeClass("fetchingdata");
        mButtonElement.removeClass("fetchingdata");
      }
      else {
        // Not Read-Only
        mElement.removeClass("is-readonly");
        mElement.removeAttr("readonly");
        mElement.removeClass("fetchingdata");
        mButtonElement.removeClass("fetchingdata");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Dropdown button
      if (mOptions.showDropdown) {
        mButtonElement.show();
      }
      else {
        mButtonElement.hide();
      }

      // Description
      if (mDescriptionElement) {
        if (mOptions.showDescription) {
          mDescriptionElement.show();
        }
        else {
          mDescriptionElement.hide();
        }
      }

      // Hyperlink Content (only when read-only)
      if (mOptions.hyperlinkContent) {
        mElement.addClass("is-hyperlink");
        mElement.addClass("is-hyperlink");
      }
      else {
        mElement.removeClass("is-hyperlink");
      }

      // Other
      mElement.attr("maxLength", mOptions.maxLength == 0 ? "" : mOptions.maxLength);
      mElement.css({ width: mOptions.width });
      mElement.attr("spellcheck", "false");

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }

      // Grid editor?
      if (mOptions.createdForGrid) {
        if (mSpecialStandardRangeName) {
          // Still need dropdown button to search
        }
        else {
          // Hide dropdown button
          mButtonElement.hide();
        }
      }
    }

    // ----------------------
    // Update the Description
    // ----------------------
    function UpdateDescription() {
      if (!mDescriptionElement || !mOptions.showDescription) return;

      // Initialise
      mDescriptionElement.removeClass("is-invalid");

      if (!Text() && mOptions.blankTipDescription) {
        mDescriptionElement.text(mOptions.blankTipDescription);
      }
      else {
        switch (mDataSourceFormat) {
          case "Array":
            // Array (must provide its own description via the DescriptionUpdate method)
            mDescriptionElement.text(mArrayDescription);
            if (mArrayDescriptionInvalid) mDescriptionElement.addClass("is-invalid");
            break;

          case "Unbound":
            // Unbound (data source is the description)
            mDescriptionElement.text(mDataSource);
            break;

          default:
            if (mSpecialStandardRangeName) {
              // Special Standard Range (requires lookup)
              var id = Text();
              if (id != mQuickSearchResultsDescriptionFromId) {
                mDescriptionElement.text("");
                mQuickSearchResultsDescriptionFromId = "";
                mQuickSearchResultsDescription = "";

                if (id) {
                  // Lookup (after short delay)
                  if (mQuickSearchResultsDescriptionTimer) {
                    window.clearTimeout(mQuickSearchResultsDescriptionTimer);
                    mQuickSearchResultsDescriptionTimer = null;
                  }
                  var t = window.setTimeout(function () {
                    window.clearTimeout(t);
                    t = null;

                    // Get description
                    var params = { standardRangeName: mSpecialStandardRangeName, id: id, sqlWhere: mSpecialStandardRangeSqlWhere };

                    widget._SystemGetString("GetStandardRangeRecordDescription", params,
                      function (data) {
                        if (data) {
                          // Parse
                          data = JSON.parse(data);

                          // Finalise
                          if (Text() == id) {
                            mQuickSearchResultsDescriptionFromId = id;
                            mQuickSearchResultsDescription = data.Description;
                            mDescriptionElement.text(mQuickSearchResultsDescription);
                            if (mOptions.limitToList && !data.Description) {
                              mDescriptionElement.addClass("is-invalid");
                              mDescriptionElement.text("!");
                            }

                            // Correct case of id
                            if (data.Id && id != data.Id) {
                              mInternalHoldChangeEvent += 1;
                              mElement.val(data.Id);
                              mInternalHoldChangeEvent -= 1;
                            }
                          }
                          else {
                            // Text has been changed!
                          }
                        }
                      },

                      function (data) {
                        widget.RegisterError("widget_ui.DBCombo: Failed to retrieve Standard Range record description: " + data);
                      }
                    );
                  }, 500);
                }
              }
            }
            else {
              // Match text in list
              var i = GetMatchIndex(mElement.val());

              if (mElement.val() == "") {
                mDescriptionElement.text("");
              }
              else if (i == -1 || i >= mListDescription.length) {
                if (mListDescription.length == 0) {
                  // List probably not loaded yet so style as invalid
                  mDescriptionElement.text("");
                }
                else {
                  // Invalid
                  if (mOptions.limitToList) {
                    mDescriptionElement.text("!");
                    mDescriptionElement.addClass("is-invalid");
                  }
                  else {
                    mDescriptionElement.text("");
                    mDescriptionElement.removeClass("is-invalid");
                  }
                }
              }
              else {
                mDescriptionElement.text(mListDescription[i]);
              }
            }
            break;
        }
      }
    }

    // ---------------
    // Update the List
    // ---------------
    function UpdateList() {
      // Clear existing
      mDropdownPanel.Clear();
      mList = [];
      mListDescription = [];

      switch (mDataSourceFormat) {
        case "":
          break;

        case "Array":
          UpdateList_Array();
          break;

        case "Collection":
          if (mSpecialStandardRangeName) {
            UpdateList_CollectionSpecialStandardRange();
          }
          else {
            UpdateList_Collection();
          }
          break;

        case "CodeDescriptionList":
          UpdateList_CodeDescriptionList();
          break;

        default:
          window.alert("widget.UI.DBCombo.UpdateList: Unsupported Data Source format");
          break;
      }

      // Add filter box
      if (mListElement && mList.length > 10) {
        if (mFilterBoxInterval) {
          window.clearInterval(mFilterBoxInterval);
          mFilterBoxInterval = null;
        }

        mFilterBoxElement = $("<caption class='is-table-filter'><input type='search' placeholder='Type to filter list' style='width:100%' autocomplete='off' spellcheck='false'/></caption>");
        $("tbody", mListElement).before(mFilterBoxElement);
        mFilterBoxInterval = window.setInterval(function () {
          var e = $("input", mFilterBoxElement);
          if (e.val() != mFilterText) {
            ApplyFilter(e.val());
          }
        }, 200);

        // Allow cursor down in filter box to enter grid (actually, refocus the textbox control since this handles grid up/down)
        mFilterBoxElement.keydown(function (e) {
          switch (e.which) {
            case 40:
              Focus();
              break;
          }
        });
      }

      // Update description
      UpdateDescription();

      // No longer dirty
      mListDirty = false;
    }

    function UpdateList_Array() {
      var options;

      // Initialise
      options = "<table style='width:100%'>";
      options += "<tbody>";

      // List
      for (var i = 0; i < mDataSource.length; i++) {
        // Record list and description values
        mList[i] = mDataSource[i];
        mListDescription[i] = "";

        // Update display table
        options += "<tr class='is-selectable'>";
        if (mDataSource[i]) {
          options += "<td>" + widget.UI.HtmlEncode(mDataSource[i]) + "</td>";
        }
        else {
          options += "<td>&nbsp;</td>";
        }
        options += "</tr>";
      }

      // Finalise
      options += "</tbody>";
      options += "</table>";
      mListElement = $(options);

      // Handle events
      $("tbody > tr", mListElement).bind("click", function (e) {
        var i = $("tbody > tr", mListElement).index(e.delegateTarget);
        if (i >= 0 && i < mList.length) {
          mElement.val(mList[i]);
          //UpdateDescription();
          if (!mOptions.usePicker) DropdownHide(true);
          NotifyChange(true, true);
          if (mOptions.usePicker) {
            UpdateListSelectedItem();
            SharedPickerPanel().Hide(true);
          }
        }
      });

      // Append
      if (!mOptions.usePicker) mDropdownPanel.Append(mListElement);
    }

    function UpdateList_CodeDescriptionList() {
      var options;

      // Initialise
      options = "<table style='width:100%'>";
      if (mOptions.showColumnHeadings && mColumnHeaderCode) {
        options += "<thead>";
        options += "<tr><th>" + widget.UI.HtmlEncode(mColumnHeaderCode) + "</th><th>" + widget.UI.HtmlEncode(mColumnHeaderDescription) + "</th></tr>";
        options += "</thead>";
      }
      options += "<tbody>";

      // List
      for (var i = 0; i < mDataSource.length; i++) {
        // Record list and description values
        mList[i] = mDataSource[i].Code;
        mListDescription[i] = mDataSource[i].Description;

        // Update display table
        options += "<tr class='is-selectable'>";
        options += "<td>" + widget.UI.HtmlEncode(mDataSource[i].Code) + "</td>";
        options += "<td>" + widget.UI.HtmlEncode(mDataSource[i].Description) + "</td>";
        options += "</tr>";
      }

      // Finalise
      options += "</tbody>";
      options += "</table>";
      mListElement = $(options);

      // Handle events
      $("tbody > tr", mListElement).bind("click", function (e) {
        var i = $("tbody > tr", mListElement).index(e.delegateTarget);
        if (i >= 0 && i < mList.length) {
          mElement.val(mList[i]);
          UpdateDescription();
          if (!mOptions.usePicker) DropdownHide(true);
          DropdownHide(true);
          NotifyChange(true, true);
          if (mOptions.usePicker) {
            UpdateListSelectedItem();
            SharedPickerPanel().Hide(true);
          }
        }
      });

      // Append
      if (!mOptions.usePicker) mDropdownPanel.Append(mListElement);
    }

    function UpdateList_Collection() {
      var displayColumns;
      var options;

      // Split display columns
      if (mDataSourceDisplayColumns) {
        displayColumns = mDataSourceDisplayColumns.split(",");
      }
      else {
        // Just in case!
        displayColumns = [];
      }

      // Determine data types
      var dataTypes = [displayColumns.length];
      for (var i = 0; i < displayColumns.length; i++) {
        dataTypes[i] = "";

        for (var j = 0; j < mDataSource.length; j++) {
          var v = mDataSource[j][displayColumns[i]];
          var dt = "";
          if (typeof v == "boolean") {
            dt = "Boolean";
          }
          else if (displayColumns[i] && displayColumns[i].toUpperCase().indexOf("DATE") != -1) {
            dt = "Date";
          }
          else {
            dt = "";
          }

          if (dt != dataTypes[i]) {
            if (dataTypes[i] == "") {
              dataTypes[i] = dt;
            }
            else {
              dataTypes[i] = "";
              break;
            }
          }
        }
      }

      // Initialise
      options = "<table style='width:100%'>";

      // Headings
      if (mOptions.showColumnHeadings && displayColumns.length != 0) {
        options += "<thead><tr>";
        for (var i = 0; i < displayColumns.length; i++) {
          // Abbreviate column headings (useful for clarity and particularly picker panels which are quite narrow)
          var s = displayColumns[i];
          var suffix = "";
          if (s == mDataSourceIdColumn && s != "Value") {
            // ID column
            s = "Code";
          }
          else if (s.endsWith("Resolved")) {
            // Remove 'Resolved' from the end, e.g., 'Description Resolved'
            s = s.substr(0, s.length - 8);
            suffix = "+";
          }
          else if (s.endsWith("Full")) {
            // Remove 'Full' from the end, e.g., 'Description Full'
            s = s.substr(0, s.length - 4);
            suffix = "+";
          }
          else if (s.endsWith("TypeText")) {
            // Remove 'Text' from the end, e.g., 'Script Type Text'
            s = s.substr(0, s.length - 4);
          }
          else if (s.startsWith("Master") && s.endsWith("Id")) {
            // Shorten heading to 'Master', e.g., 'Master External Party Id'
            s = "Master";
          }

          // Header Caption and formatting
          switch (dataTypes[i]) {
            case "Boolean":
              options += "<th align='center' style='width:1em'><nobr>" + widget.UI.HtmlEncode(SplitWordsAtCapitals(s)) + suffix + "</nobr></th>";
              break;

            case "Date":
              options += "<th align='right'>" + widget.UI.HtmlEncode(SplitWordsAtCapitals(s)) + suffix + "</th>";
              break;

            default:
              options += "<th>" + widget.UI.HtmlEncode(SplitWordsAtCapitals(s)) + suffix + "</th>";
              break;
          }
        }
        options += "</tr></thead>";
      }
      options += "<tbody>";

      // List
      for (var i = 0; i < mDataSource.length; i++) {
        // Record list and description values
        mList[i] = mDataSource[i][mDataSourceIdColumn];
        mListDescription[i] = mDataSource[i][mDataSourceDescriptionColumn];

        // Update display table
        options += "<tr class='is-selectable'>";
        for (var j = 0; j < displayColumns.length; j++) {
          switch (dataTypes[j]) {
            case "Boolean":
              if (mDataSource[i][displayColumns[j]]) {
                options += "<td align='center' class='is-symbol-tick' style='color:green'></td>";
              }
              else {
                options += "<td align='center' class='is-symbol-cross' style='color:red'></td>";
              }
              break;

            case "Date":
              // Date (e.g., Tax Period on Tax Period Reconciliation parameters)
              if (mDataSource[i][displayColumns[j]]) {
                // Dates may actually be String values, i.e., formatted server-side, e.g., the Bank Entry widget
                var cv = mDataSource[i][displayColumns[j]];
                if (typeof cv == "string" && (cv.indexOf(" ") != -1 || cv.indexOf("M") != -1 || cv.indexOf("/") != -1)) {
                  // Looks like a string formatted to display a date
                  options += "<td>" + HtmlEncode(cv) + "</td>";
                }
                else {
                  options += "<td>" + Runtime_FormatDate(cv) + "</td>";
                }
              }
              else {
                options += "<td>&nbsp;</td>";
              }
              break;

            default:
              // String
              if (mDataSource[i][displayColumns[j]]) {
                options += "<td>" + widget.UI.HtmlEncode(mDataSource[i][displayColumns[j]]) + "</td>";
              }
              else {
                options += "<td>&nbsp;</td>";
              }
              break;
          }
        }
        options += "</tr>";
      }

      // Finalise
      options += "</tbody>";
      options += "</table>";
      mListElement = $(options);

      // Handle events
      $("tbody > tr", mListElement).bind("click", function (e) {
        var i = $("tbody > tr", mListElement).index(e.delegateTarget);
        if (i >= 0 && i < mList.length) {
          mElement.val(mList[i]);
          UpdateDescription();
          if (!mOptions.usePicker) DropdownHide(true);
          NotifyChange(true, true);
          if (mOptions.usePicker) {
            UpdateListSelectedItem();
            SharedPickerPanel().Hide(true);
          }
        }
      });

      // Append
      if (!mOptions.usePicker) mDropdownPanel.Append(mListElement);
    }

    function UpdateList_CollectionSpecialStandardRange() {
      // Standard Range is actually a form of "Quick Search"
      mListElement = $("<div style='min-height:120px; min-width:320px'></div>");
      var divTop = $("<div style='display:flex; flex-direction:row; align-content:stretch'></div>");
      var input = $("<input type='text' style='font-size:13px !important; border-radius:0 !important; border:1px solid transparent !important; height:28px !important; line-height:26px !important; background-color:white !important'/>");
      var btn = $("<button class='dbcombo-search'/>");
      var divGrid = $("<div style='position:absolute; top:29px !important; left:0; right:0;bottom:0;overflow:auto;'></div>");

      switch (mSpecialStandardRangeName.toUpperCase()) {
        case "CLIENTS":
          input.attr("placeholder", "E.g. code, name, date of birth, email, phone");
          break;

        case "SECURITYSTMTS":
          input.attr("placeholder", "E.g. code, name, serial number, registration");
          break;

        case "WORKFLOWS":
          input.attr("placeholder", "E.g. code");
          break;

        default:
          input.attr("placeholder", "E.g. code, name");
          break;
      }

      divTop.append(input);
      divTop.append(btn);
      mListElement.append(divTop);
      mListElement.append(divGrid);

      mQuickSearchResultsGrid = new Grid(divGrid, {
        showColumnHeaders: false,
        stickyHeader: false,

        onAfterRowActivate: UpdateList_CollectionSpecialStandardRange_AfterRowActivate,
        onRowDrilldown: UpdateList_CollectionSpecialStandardRange_RowDrilldown,
        onInitialiseRow: UpdateList_CollectionSpecialStandardRange_InitialiseRow,
      });
      mQuickSearchResultsGrid.AddColumnCode("Id", { caption: "Code" });
      mQuickSearchResultsGrid.AddColumnString("Name", { caption: "Description" });
      mQuickSearchResultsGrid.AddColumnString("Info", { caption: "Information", align: "right", colour: "gray" });
      mQuickSearchResultsGrid.Refresh();

      var txtSearch = TextBox(input, {
        onEnterKey: function () { UpdateList_CollectionSpecialStandardRange_Search(txtSearch.Text()); },
      });
      txtSearch.WrapperElement().css("flex-grow", "1");
      mQuickSearchResultsTextBox = txtSearch;

      // Allow cursor down in Quick Search to enter grid
      txtSearch.Element().keydown(function (e) {
        switch (e.which) {
          case 27:
            if (txtSearch.Text()) {
              txtSearch.Text("");
            }
            else {
              DropdownHide(true);
            }
            return false; // Prevent default key action

          case 40:
            if (mQuickSearchResults && mQuickSearchResults.Results.length != 0) {
              mQuickSearchResultsGrid.Focus();
              if (mQuickSearchResultsGrid.ActiveDataRowIndex() == -1) mQuickSearchResultsGrid.ActiveDataRowIndex(0);
            }
            return false; // Prevent default key action
        }
      });

      // Enter on grid should drill down
      mQuickSearchResultsGrid.Element().keydown(function (e) {
        switch (e.which) {
          case 13:
            if (mQuickSearchResultsGrid.ActiveDataRowIndex() != -1) {
              mQuickSearchResultsGrid.PerformRowDrilldown();
            }
            break;
        }
      });

      // Search button
      btn.click(function () { txtSearch.Focus(); UpdateList_CollectionSpecialStandardRange_Search(txtSearch.Text()); });

      // Append
      if (!mOptions.usePicker) mDropdownPanel.Append(mListElement);
    }
    function UpdateList_CollectionSpecialStandardRange_Search(query) {
      // Clear?
      if (!query) {
        mQuickSearchResultsGrid.Visible(false);
        return;
      }
      else {
        mQuickSearchResultsGrid.Visible(true);
      }

      // Search
      var params = {
        standardRangeName: mSpecialStandardRangeName,
        query: query,
        sqlWhere: mSpecialStandardRangeSqlWhere,
      };

      widget._SystemGetString("GetStandardRangeQuickSearchResults", params,
        function (data) {
          if (data) {
            // Parse
            mQuickSearchResults = JSON.parse(data);

            // Show/ Hide "Info" column
            var showInfo = false;
            for (var i = 0; i < mQuickSearchResults.Results.length; i++) {
              if (mQuickSearchResults.Results[i].Info) {
                showInfo = true;
                break;
              }
            }
            mQuickSearchResultsGrid.ColumnVisible("Info", showInfo);

            // Bind Grid
            mQuickSearchResultsGrid.VirtualDataRefresh(mQuickSearchResults.Results);
            mQuickSearchResultsGrid.ActiveDataRowIndex(-1);
          }

          // Callback
          //if (callback) callback();
        },

        function (data) {
          widget.RegisterError("widget_ui.DBCombo: Failed to retrieve Quick Search results for Standard Range: " + data);

          // Failed to get results. Not much we can do!
          //if (callback) callback();
        }
      );
    }
    function UpdateList_CollectionSpecialStandardRange_InitialiseRow(e) {
      var item = mQuickSearchResults.Results[e.row.listIndex];

      // Update cells
      e.row.cells.Id.value = item.Id;
      e.row.cells.Name.value = item.Name;
      e.row.cells.Info.value = item.Info;
    }
    function UpdateList_CollectionSpecialStandardRange_AfterRowActivate(e) {
      if (mQuickSearchResults && mQuickSearchResults.Results && mQuickSearchResultsGrid.ActiveDataRowIndex() != -1) {
        var item = mQuickSearchResults.Results[mQuickSearchResultsGrid.ActiveDataRowIndex()];

        if (item) mElement.val(item.Id);
        UpdateDescription();
        NotifyChange(true, e.activatedFromClick);
      }
    }
    function UpdateList_CollectionSpecialStandardRange_RowDrilldown(e) {
      mDropdownPanel.Hide();
      mElement.focus();
    }

    // ---------------------
    // PRIVATE: Apply filter
    // ---------------------
    function ApplyFilter(filterText) {
      mFilterText = filterText;
      mListFilteredOutIndexes = [];

      if (mDataSource && mListElement) {
        // Clear all filters
        $("tbody > tr", mListElement).removeClass("is-filtered-out");

        if (mFilterText) {
          // Split filter criteria
          var criteria = mFilterText.toUpperCase().split(" ");
          if (criteria.length > 0) {
            // Get all rows
            var rows = $("tbody > tr", mListElement);

            for (var i = 0; i < rows.length; i++) {
              // Get row
              var row = rows[i];

              // Check criteria exists (ALL criteria must exist in a row)
              var foundInRecord = true;
              for (var crit = 0; crit < criteria.length; crit++) {
                var critText = criteria[crit];
                var found = false;
                var rowCells = $("td", row);

                if (critText && critText != " ") {
                  for (var col = 0; col < rowCells.length; col++) {
                    var colText = $(rowCells[col]).text();

                    if (colText && colText.toUpperCase().indexOf(critText) != -1) {
                      found = true;
                      break;
                    }
                  }
                }

                if (!found) {
                  foundInRecord = false;
                  break;
                }
              }

              // Filter row out?
              if (!foundInRecord) {
                $(rows[i]).addClass("is-filtered-out");
                mListFilteredOutIndexes.push(i);
              }
            }
          }

          // Ensure active row is visible
          var listIndex = ListIndex();
          if (listIndex >= 0 && listIndex < rows.length) {
            if ($(rows[listIndex]).hasClass("is-filtered-out")) {
              var firstVisible = -1;

              for (var i = 0; i < rows.length; i++) {
                if (!$(rows[i]).hasClass("is-filtered-out")) {
                  firstVisible = i;
                  break;
                }
              }

              // When setting List Index, ensure the value in the textbox does not change!
              $("tr.is-sel", mListElement).removeClass("is-sel");
              if (firstVisible >= 0 && firstVisible < rows.length) $(rows[firstVisible]).addClass("is-sel");
              //ListIndex(firstVisible);
              //UpdateListSelectedItem();
            }
          }
        }
      }
    }

    // -------------------------------
    // Update the List's Selected Item
    // -------------------------------
    function UpdateListSelectedItem() {
      var i = GetMatchIndex(mElement.val(), false);

      // Initialise
      $("tr.is-sel", mListElement).removeClass("is-sel");

      // Highlight selected
      if (i >= 0 && i < mList.length) {
        // Highlight
        var e = $($("tbody > tr", mListElement)[i]);
        e.addClass("is-sel");

        // Ensure visible
        if (mOptions.createdForGrid) {
          // When this is shown from a grid, scrolling issues can occur so provide the ACTUAL parent control that is/ may be scrollable (J030277)
          e.ScrollElementIntoView(true, null, { scrollParent: mDropdownPanel.Element() });
        }
        else {
          e.ScrollElementIntoView(true);
        }
      }
    }

    // -------------
    // Show Dropdown
    // -------------
    function DropdownShow() {
      // Update List
      if (mListDirty) UpdateList();

      if (mOptions.usePicker) {
        // ------------
        // Picker Panel
        // ------------
        // Get Caption
        var caption = mOptions.pickerCaption;
        if (!caption && mLabelElement) {
          caption = mLabelElement.text();
          if (caption) {
            caption = "Select " + caption;
            if (caption.endsWith(":")) caption = caption.substr(0, caption.length - 1);

          }
        }
        if (!caption) caption = "Select Item";

        // Show Picker Panel
        SharedPickerPanel().Toggle({
          closeFocusElement: _self,
          sourceButtonElement: mButtonElement,
          caption: caption,
          contentElement: mListElement,

          onKeyDown: function (e) {
            switch (e.keyCode) {
              case 35: // End
                ListIndex(mList.length - 1);
                UpdateListSelectedItem();
                break;

              case 36: // Home
                ListIndex(0);
                UpdateListSelectedItem();
                break;

              case 38: // Cursor Up
                ListIndexChange(-1);
                UpdateListSelectedItem();
                break;

              case 40: // Cursor Down
                ListIndexChange(1);
                UpdateListSelectedItem();
                break;
            }
          }
        });
      }
      else {
        // -------------
        // Dropdown List
        // -------------
        mDropdownPanel.AttachedControl(_self);

        if (mSpecialStandardRangeName) {
          mDropdownPanel.Show(0, true); // Full height
          mDropdownPanel.WidthResizeFromParent(800);
        }
        else {
          mDropdownPanel.Show();
        }

        // Focus "Search" TextBox
        if (mSpecialStandardRangeName) {
          mQuickSearchResultsTextBox.Focus();
        }
        else {
          // Focus TextBox
          if (!mIsSmallMobileBrowser) {
            mElement.focus();
            mElement.select();
          }
        }
      }

      // Highlight selected item in list
      UpdateListSelectedItem();

      // Showing
      mDropdownShowing = true;

      // Pre-populate and Search?
      if (mSpecialStandardRangeName && mQuickSearchResultsTextBox && Text()) {
        if (!mQuickSearchResultsTextBox.Text()) {
          var searchText = Text();
          mQuickSearchResultsTextBox.Text(searchText);
          mQuickSearchResultsTextBox.Focus();
          UpdateList_CollectionSpecialStandardRange_Search(searchText);
        }
      }
    }

    // ----------------------------
    // PUBLIC: Is Dropdown Showing?
    // ----------------------------
    function DropdownShowing() {
      return mDropdownShowing;
    }

    // -------------
    // Hide Dropdown
    // -------------
    function DropdownHide(focus) {
      mDropdownPanel.Hide();

      if (focus) {
        mElement.focus();
        mElement.select();
      }

      // Not Showing
      mDropdownShowing = false;
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return mElement.val() != mTextOriginal;
    }

    // -----------------------------------------------------
    // PUBLIC: Update the Description used for Array sources
    // -----------------------------------------------------
    function DescriptionUpdate(description, descriptionIsHtml, invalid) {
      if (!invalid) invalid = false;
      mArrayDescription = description;
      mArrayDescriptionInvalid = invalid;
      UpdateDescription();
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange(changedFromPopup, changedFromPopupClick) {
      // Already in change
      if (mInternalHoldChangeEvent) return;
      mInternalHoldChangeEvent += 1;

      // Clear value if not in list (never want to notify with an invalid value by accident)
      if (mSpecialStandardRangeName) {
        // Never clear since limiting to list does not make sense with 'Special' ranges such as Accounts
      }
      else if (mOptions.limitToList && !ListExists(mElement.val())) {
        mElement.val("");
        if (mDescriptionElement) mDescriptionElement.text("");
      }

      // Ensure Descripiton is up-to-date so, if GetDescription() is called from the Change event, it is accurate (if not asyc) - J033121
      if (!mSpecialStandardRangeName) UpdateDescription();

      // Notify
      var e = { ChangeHandled: false, TextOriginal: mTextOriginal, ChangedFromPopup: changedFromPopup, ChangedFromPopupClick: changedFromPopupClick || false };
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset TextOriginal?
      if (e.ChangeHandled) mTextOriginal = mElement.val();

      // No longer in change
      mInternalHoldChangeEvent -= 1;
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value === undefined) {
        // Get
        return mOptions.allowBlank;
      }
      else {
        // Set
        if (value != mOptions.allowBlank) {
          mOptions.allowBlank = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------
    // PUBLIC: BlankTip property
    // -------------------------
    function BlankTip(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankTip;
      }
      else {
        // Set
        mOptions.blankTip = value;

        // Update element
        UpdateElement();
      }
    }

    // ------------------------------------
    // PUBLIC: BlankTipDescription property
    // ------------------------------------
    function BlankTipDescription(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankTipDescription;
      }
      else {
        // Set
        mOptions.blankTipDescription = value;

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // ----------------------------------------------------------------------------------------
    // PUBLIC: Get the Description (since this MAY be fetched asynchronously, use with caution)
    // ----------------------------------------------------------------------------------------
    function GetDescription() {
      if (!mDescriptionElement) return "";

      if (mOptions.showDescription) {
        return mDescriptionElement.text();
      }
      else {
        switch (mDataSourceFormat) {
          case "Collection":
            if (!mSpecialStandardRangeName && mElement.val()) {
              // Match text in list
              var i = GetMatchIndex(mElement.val());

              if (i >= 0 && i < mListDescription.length) {
                return mListDescription[i];
              }
            }
            break;
            
        }

        return "";
      }
    }

    // ----------------
    // Find Match Index
    // ----------------
    function GetMatchIndex(value, partial) {
      if (partial && value.length == 0) return -1;

      for (var i = 0; i < mList.length; i++) {
        if (partial) {
          if (mList[i].substr(0, value.length).toUpperCase() == value.toUpperCase()) return i;
        }
        else {
          if (mList[i] == value) return i;
        }
      }

      return -1;
    }

    // ---------------------------
    // PUBLIC: List Index property
    // ---------------------------
    function ListIndex(value) {
      if (value === undefined) {
        // Get
        return GetMatchIndex(mElement.val(), false);
      }
      else {
        // Set
        if (value < 0 || value > mList.length - 1) {
          Text("");
        }
        else {
          Text(mList[value]);
        }

        mTextOriginal = mElement.val();
      }
    }

    // -----------------
    // Change List Index
    // -----------------
    function ListIndexChange(i, visibleRowsOnly) {
      // Initialise
      var index = ListIndex();

      // Visible row?
      if (visibleRowsOnly) {
        // Skip hidden rows
        if (i > 0) {
          for (var j = index + 1; j < mList.length; j++) {
            if (mListFilteredOutIndexes.includes(j)) {
              // Keep going
            }
            else {
              // Found
              index = j;
              break;
            }
          }
        }
        else {
          for (var j = index - 1; j >= 0; j--) {
            if (mListFilteredOutIndexes.includes(j)) {
              // Keep going
            }
            else {
              // Found
              index = j;
              break;
            }
          }
        }
      }
      else {
        // Increment/ Decrement
        index += i;
        if (index < 0) {
          index = 0;
        }
        else if (index > mList.length - 1) {
          index = mList.length - 1;
        }
      }

      // Update Text
      TextSet(mList[index], false, true);
    }

    // ------------------------------
    // PUBLIC: Limit To List property
    // ------------------------------
    function LimitToList(value) {
      if (value === undefined) {
        // Get
        return mOptions.limitToList;
      }
      else {
        // Set
        if (value != mOptions.limitToList) {
          mOptions.limitToList = (value == true);
        }
      }
    }

    // --------------------------------------------------
    // PUBLIC: Check to see if a value exists in the List
    // --------------------------------------------------
    function ListExists(value, ignoreCase) {
      // Initialise
      ignoreCase = ignoreCase ? true : false;
      value += "";

      if (ignoreCase) {
        value = value.toUpperCase();
        for (var i = 0; i < mList.length; i++) {
          if (mList[i].toUpperCase() == value) return true;
        }
      }
      else {
        for (var i = 0; i < mList.length; i++) {
          if (mList[i] == value) return true;
        }
      }

      return false;
    }

    // ----------------------------------
    // PUBLIC: Set List from a CSV String
    // ----------------------------------
    function ListFromCsvString(value) {
      mDataSource = ArrayFromCsvString(value);
      mDataSourceFormat = "Array";
      mListDirty = true;
      //UpdateList();
    }

    // --------------------------
    // PUBLIC: MaxLength property
    // --------------------------
    function MaxLength(value) {
      if (value === undefined) {
        // Get
        return mOptions.maxLength;
      }
      else {
        // Set
        mOptions.maxLength = value;

        // Update element
        UpdateElement();
      }
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ------------------------------------------
    // PUBLIC: Refresh from Code Description List
    // ------------------------------------------
    function RefreshFromCodeDescriptionList(value, columnHeaderCode, columnHeaderDescription) {
      if (value !== undefined) {
        mDataSourceFormat = "CodeDescriptionList";
        mDataSource = value;

        if (columnHeaderCode !== undefined) mColumnHeaderCode = columnHeaderCode;
        if (columnHeaderDescription !== undefined) mColumnHeaderDescription = columnHeaderDescription;

        UpdateList();
      }
    }

    // -------------------------------
    // PUBLIC: Refresh from Collection
    // -------------------------------
    function RefreshFromCollection(value, idColumn, descriptionColumn, displayColumns) {
      if (value !== undefined) {
        mDataSourceFormat = "Collection";
        mDataSource = value;
        mDataSourceIdColumn = idColumn;
        mDataSourceDescriptionColumn = descriptionColumn;
        if (displayColumns) {
          mDataSourceDisplayColumns = displayColumns;
        }
        else {
          mDataSourceDisplayColumns = idColumn;
          if (descriptionColumn) mDataSourceDisplayColumns += "," + descriptionColumn;
        }
        mSpecialStandardRangeName = "";

        UpdateList();
      }
    }

    // -----------------------------------
    // PUBLIC: Refresh from Standard Range
    // -----------------------------------
    function RefreshFromStandardRange(standardRangeName, sqlWhere, includeInactive, alwaysIncludeId, displayColumns, callback) {
      if (standardRangeName) {
        mDataSourceFormat = "Collection";
        mDataSource = null;
        mDataSourceIdColumn = "";
        mDataSourceDescriptionColumn = "";
        mDataSourceDisplayColumns = "";
        mSpecialStandardRangeName = "";
        mSpecialStandardRangeSqlWhere = "";

        // Bypass Special Standard Ranges, i.e., always display list
        var bypass = false;
        if (standardRangeName.startsWith("@")) {
          bypass = true;
          standardRangeName = standardRangeName.substr(1);
        }
        else if (mOptions.forceDropdown) {
          bypass = true;
        }

        // Special Standard Ranges that require a Search form
        if (!bypass) {
          var s = standardRangeName.toUpperCase();
          if (s.substr(0, 8) == "ACCOUNTS") {
            mSpecialStandardRangeName = standardRangeName;
            mSpecialStandardRangeSqlWhere = sqlWhere;
            mListDirty = true;
            UpdateDescription();
            if (callback) callback();
            return;
          }
          else if (s.substr(0, 11) == "ACCOUNTAPPS" && s != "ACCOUNTAPPSUBSTATUSES") {
            mSpecialStandardRangeName = standardRangeName;
            mSpecialStandardRangeSqlWhere = sqlWhere;
            mListDirty = true;
            UpdateDescription();
            if (callback) callback();
            return;
          }
          else if (s.substr(0, 7) == "CLIENTS") {
            mSpecialStandardRangeName = standardRangeName;
            mSpecialStandardRangeSqlWhere = sqlWhere;
            mListDirty = true;
            UpdateDescription();
            if (callback) callback();
            return;
          }
          else if (s.substr(0, 13) == "SECURITYSTMTS") {
            mSpecialStandardRangeName = standardRangeName;
            mSpecialStandardRangeSqlWhere = sqlWhere;
            mListDirty = true;
            UpdateDescription();
            if (callback) callback();
            return;
          }
          else if (s.substr(0, 9) == "WORKFLOWS") {
            mSpecialStandardRangeName = standardRangeName;
            mSpecialStandardRangeSqlWhere = sqlWhere;
            mListDirty = true;
            UpdateDescription();
            if (callback) callback();
            return;
          }
        }

        // Indicate that data is being fetched
        SetFetchingData(true);

        // Get Standard Range
        var params = { standardRangeName: standardRangeName };
        if (sqlWhere) params.sqlWhere = sqlWhere;
        if (includeInactive) params.includeInactive = includeInactive;
        if (alwaysIncludeId) params.alwaysIncludeId = alwaysIncludeId;
        if (displayColumns) params.displayColumns = displayColumns;

        widget._SystemGetString("GetStandardRange", params,
          function (data) {
            if (data) {
              // Parse
              data = JSON.parse(data);

              // Convert Rows array into an array of objects
              // NOTE: Transferring an array of values is more compact than an array of objects!
              var newRows = [];
              for (var i = 0; i < data.Rows.length; i++) {
                var row = {};
                var item = data.Rows[i];

                for (var j = 0; j < data.Columns.length; j++) {
                  row[data.Columns[j].Name] = item[j];
                }

                newRows.push(row);
              }

              // Refresh
              RefreshFromCollection(newRows, data.IdColumn, data.DescriptionColumn, displayColumns);

              // Finalise
              SetFetchingData(false);
            }

            // Callback
            if (callback) callback();
          },

          function (data) {
            // Parse
            widget.RegisterError("widget_ui.DBCombo: Failed to retrieve Standard Range: " + data);

            // Failed to get list. Not much we can do!
            if (callback) callback();
          }
        );
      }
    }

    // -----------------------------
    // PUBLIC: ShowDropdown property
    // -----------------------------
    function ShowDropdown(value) {
      if (value === undefined) {
        // Get
        return mOptions.showDropdown;
      }
      else {
        // Set
        if (value != mOptions.showDropdown) {
          mOptions.showDropdown = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------------------------------------------------------------------------------
    // PUBLIC: Indicates whether this has been refreshed for a Special Standard Range, e.g., Accounts
    // ----------------------------------------------------------------------------------------------
    function IsSpecialStandardRange() {
      return mSpecialStandardRangeName != "";
    }

    // -----------------------
    // PUBLIC: Refresh Unbound
    // -----------------------
    function RefreshUnbound(value, description) {
      // Initialise
      if (!description) description = "";
      mDataSourceFormat = "Unbound";
      mDataSource = description;

      // Update Element
      mElement.val(value);

      // Update description
      UpdateDescription();

      // Finalise
      mTextOriginal = value;
    }

    // ------------------------------------
    // PUBLIC: Set the 'Fetching Data' Mode
    // ------------------------------------
    function SetFetchingData(value) {
      mFetchingData = value;

      // Update
      UpdateElement();
    }

    // --------------------------------
    // PUBLIC: ShowDescription property
    // --------------------------------
    function ShowDescription(value) {
      if (value === undefined) {
        // Get
        return mOptions.showDescription;
      }
      else {
        // Set
        mOptions.showDescription = value;

        // Refresh
        UpdateElement();
      }
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return Runtime_GetString(mElement);
      }
      else {
        // Set
        if (value != mElement.val()) {
          mInternalHoldChangeEvent += 1;
          mElement.val(value);
          mInternalHoldChangeEvent -= 1;

          // Update description
          UpdateDescription();
        }

        mTextOriginal = value;
      }
    }

    // -------------------
    // Set text internally
    // -------------------
    function TextSet(value, forceEvent, changedFromPopup) {
      // Raise OnChange event
      if (value != mElement.val() || forceEvent) {
        // Update text
        mInternalHoldChangeEvent += 1;
        mElement.val(value);
        mInternalHoldChangeEvent -= 1;

        // Notify
        NotifyChange(changedFromPopup);
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      var parentWidth;
      var width = mOptions.width;
      var descriptionWidth = 0;

      // Wrapper
      if (mOptions.showDescription) {
        mDescriptionElement.show();
      }
      else {
        mWrapperElement.css("width", "100%");
        mDescriptionElement.hide();
      }

      // Textbox (remember, we need to cater for information lists)
      if (fullWidth || mOptions.maxLength == 0 || (mOptions.maxLength >= 50 && !mOptions.showDescription)) {
        width = "100%";
      }
      else {
        //TODO: Smarter than this, i.e., don't use 14!
        if (width && width != "auto") {
          // Width specified (applies to textbox portion only)
        }
        else {
          // Calculate
          if (mOptions.maxLength) {
            if (mOptions.maxLength <= 4) {
              width = ((mOptions.maxLength * 0.8) + 2) + "em"; // Add 2 to account for the dropdown button
            }
            else {
              width = (mOptions.maxLength * 0.8) + "em";
            }
          }
        }
      }

      mElement.css({ width: width });
      if (width == "100%" && !mOptions.showDescription) {
        mWrapperElement.css("width", "100%");
      }
      else {
        mWrapperElement.css("width", "");
      }

      // Use flex-box layout for auto-generated descriptions - saves messing about with parent widths etc that keep breaking in different browser versions!
      if (mDescriptionElement && mOptions.showDescription && mOptions.descriptionElement == "auto") {
        //mWrapperElement.css("border", "1px solid green");
        mWrapperElement.css("width", "100%");
        mWrapperElement.css("position", "relative");
        mWrapperElement.css("display", "flex");
        mWrapperElement.css("flex-direction", "row");
        mWrapperElement.css("white-space", "");

        mElement.css("flex-grow", "0");
        mElement.css("max-width", width);

        mButtonElement.css("flex-grow", "0");

        mDescriptionElement.css("flex-grow", "1");
        mDescriptionElement.css("overflow", "hidden");
        mDescriptionElement.css("position", "relative");
      }
      else {
        //mWrapperElement.css("border", "1px solid blue");
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.DBCombo.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "DBCombo",

      AllowBlank: AllowBlank,
      AutoReadOnly: AutoReadOnly,
      BlankTip: BlankTip,
      BlankTipDescription: BlankTipDescription,
      Caption: Caption,
      Changed: Changed,
      DescriptionUpdate: DescriptionUpdate,
      DropdownShow: DropdownShow,
      DropdownShowing: DropdownShowing,
      Element: Element,
      Focus: Focus,
      GetDescription: GetDescription,
      IsSpecialStandardRange: IsSpecialStandardRange,
      LimitToList: LimitToList,
      ListExists: ListExists,
      ListFromCsvString: ListFromCsvString,
      ListIndex: ListIndex,
      MaxLength: MaxLength,
      ReadOnly: ReadOnly,
      RefreshFromCodeDescriptionList: RefreshFromCodeDescriptionList,
      RefreshFromCollection: RefreshFromCollection,
      RefreshFromStandardRange: RefreshFromStandardRange,
      RefreshUnbound: RefreshUnbound,
      SetFetchingData: SetFetchingData,
      ShowDescription: ShowDescription,
      ShowDropdown: ShowDropdown,
      Text: Text,
      Visible: Visible,
      VisibleRow: VisibleRow,
      WidthResizeFromParent: WidthResizeFromParent,

      /* Friend (internal use only) */
      ButtonElement: function () { return mButtonElement; },
      WrapperElement: function () { return mWrapperElement; },
      UpdateElement: UpdateElement,
    };
    return _self;
  }



  // ============================
  // PUBLIC: DropdownPanel object
  // ============================
  function DropdownPanel(e, options) {

    var mAttachedElement;
    var mAttachedControl;
    var mDropdownElement;
    var mOptions;
    var mVisible = false;

    var mDropdownDocument;
    var mDropdownWindow;
    var mDropdownElementCachedHeight;

    // Extend options with defaults
    DropdownPanelDefaults = {
      animate: true,
      cssClass: "is-dropdown",
      offsetTop: 0,
      minWidthElement: null,
      popupTip: false,
      width: "auto",

      closeOnClickOutside: true,
    };
    mOptions = $.extend({}, DropdownPanelDefaults, options);

    // Get Attached Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.DropdownPanel: Attached Element '" + id + "' not found.");
      return;
    }
    mAttachedElement = $(el[0]);

    // Get window
    mDropdownDocument = document;
    mDropdownWindow = window;

    // Hide if Intersoft Website is scrolled
    if (widget.IntersoftWebsite) {
      $("body").scroll(function () {
        Hide();
      });
    }

    // Dropdown element
    if (mOptions.popupTip) {
      // Popup tip (position absolute to container)
      // TODO: WIP
      mDropdownElement = $("<div style='display:none; position:absolute; z-index:999999999999' class='" + mOptions.cssClass + "' controltype='dropdownPanel'></div>");
      mAttachedElement.append(mDropdownElement);
    }
    else {
      // Dropdown (fixed position)
      mDropdownElement = $("<div style='display:none; position:fixed; z-index:999999999999' class='" + mOptions.cssClass + "' controltype='dropdownPanel'></div>");
      mAttachedElement.after(mDropdownElement);
    }


    // ----------------------
    // PUBLIC: Append content
    // ----------------------
    function Append(e) {
      mDropdownElement.append(e);
    }

    // ---------------------------------
    // FRIEND: Attached (parent) Control
    // ---------------------------------
    function AttachedControl(value) {
      if (value === undefined) {
        // Get
        return mAttachedControl;
      }
      else {
        // Set
        mAttachedControl = value;
      }
    }

    // ---------------------------------
    // PUBLIC: Attached (parent) Element
    // ---------------------------------
    function AttachedElement() {
      return mAttachedElement;
    }

    // ---------------------
    // PUBLIC: Clear content
    // ---------------------
    function Clear() {
      mDropdownElement.children().remove();
    }

    // ---------------
    // PUBLIC: Element
    // ---------------
    function Element() {
      return mDropdownElement;
    }

    // ---------------------------
    // PUBLIC: Show dropdown panel
    // ---------------------------
    function Show(spaceRequiredBelow, fullHeight) {
      // Initialise
      mVisible = true;
      var above = false;

      if (mOptions.popupTip) {
        // Popup Tip (not positioned in the same way)
        var x = 0, y = 0;
        mDropdownElement.css({ left: x, top: y });
      }
      else {
        // Dropdown (fixed position)
        // Get Size and Position of hosting control
        var pos = mAttachedElement.offset(), x = pos.left, y = pos.top + mAttachedElement.outerHeight(), maxHeight = 0;

        // Do we have enough space to show below or do we need to display above?
        var displayBelow = true;
        if (!spaceRequiredBelow) spaceRequiredBelow = 200;
        y += mOptions.offsetTop;
        if (widget.IntersoftWebsite) {
          // Running from Intersoft Website
          maxHeight = $(window).innerHeight() - y - 4;
        }
        else {
          maxHeight = $(document).innerHeight() - y - 4;
        }
        if (maxHeight >= spaceRequiredBelow) {
          displayBelow = true;
        }
        else {
          if (pos.top >= spaceRequiredBelow) {
            // Room above
            displayBelow = false;
          }
          else {
            // Shift up
            y = $(document).innerHeight() - spaceRequiredBelow - 16; // 16 just adds a bit of a buffer
            if (y < 0) y = 0;
            mDropdownElement.css("min-height", spaceRequiredBelow);
          }
        }

        if (displayBelow) {
          // Display below
          mDropdownElement.css({ bottom: "", left: x, top: (y - window.pageYOffset) + "px", "max-height": maxHeight, height: "" });

        }
        else {
          // Display above
          above = true;
          var h = mDropdownElement.height() + 2; // +2 for border?

          // J028540 (in responsive mode, the dropdown for some reason loses its height after first displayed)
          if (mDropdownElementCachedHeight === undefined) {
            mDropdownElementCachedHeight = h;
          }
          h = mDropdownElementCachedHeight;
          if (h < 30 && mDropdownElementCachedHeight >= 30) h = mDropdownElementCachedHeight;

          var t = pos.top - h;
          if (t < 0) {
            h += t;
            t = 0;
          }
          mDropdownElement.css({ left: x, maxHeight: h, height: "100%", bottom: pos.top, top: (t - window.pageYOffset) + "px" });
        }

        // Minimum width
        if (mOptions.minWidthElement) mDropdownElement.css({ minWidth: mOptions.minWidthElement.outerWidth() });

        // Full height?
        if (fullHeight) {
          if (above) {
          }
          else {
            mDropdownElement.css("bottom", 0);
          }
        }
      }

      // Show
      mDropdownElement.removeClass("active");
      mDropdownElement.show();
      var ti = window.setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        mDropdownElement.addClass("active");
      }, 10);
    }

    // ---------------------------
    // PUBLIC: Hide dropdown panel
    // ---------------------------
    function Hide() {
      if (mVisible) {
        mVisible = false;
        mDropdownElement.hide();
        //console.log("dropdown hidden due to Hide method being called");
      }
    }

    // ---------------
    // PUBLIC: Visible
    // ---------------
    function Visible() {
      return mVisible;
    }

    // ------------------------------
    // FRIEND: Close on click outside
    // ------------------------------
    function CloseOnClickOutside() {
      return mOptions.closeOnClickOutside;
    }

    // --------------------------------
    // PUBLIC: Resize width from parent
    // --------------------------------
    function WidthResizeFromParent(maxWidthPixels) {
      if (!mVisible) return;

      if (maxWidthPixels) {
        mDropdownElement.css("max-width", maxWidthPixels + "px");
      }
      else {
        mDropdownElement.css("max-width", "");
      }

      var pos = mDropdownElement.offset(), x = pos.left;
      mDropdownElement.css("width", ($("body").innerWidth() - x) + "px");
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "DropdownPanel",

      Append: Append,
      AttachedControl: AttachedControl,
      AttachedElement: AttachedElement,
      Clear: Clear,
      Element: Element,
      Hide: Hide,
      Show: Show,
      Visible: Visible,
      WidthResizeFromParent: WidthResizeFromParent,

      /* Friend */
      CloseOnClickOutside: CloseOnClickOutside
    };

    // Tidy up (remove orphaned DropdownPanels)
    // NOTE: Do not use in HTML Widgets since they are in their own IFRAME and this can cause issues when dynamically adding controls
    //if (mDropdownWindow.__ISDropdownHandler) {
    //  for (var i = 0; i < mDropdownWindow.__ISDropdownHandler.length; i++) {
    //    var dd = mDropdownWindow.__ISDropdownHandler[i];
    //    if (dd != undefined) {
    //      var e = dd.AttachedElement();
    //      if (!$.contains(mDropdownDocument, e[0])) {
    //        dd.Element().remove();
    //        delete dd;
    //      }
    //    }
    //  }
    //}

    // Create global handler and add this dropdown panel
    if (!mDropdownWindow.__ISDropdownHandler) {
      // Array to hold all DropdownPanel objects
      mDropdownWindow.__ISDropdownHandler = new Array();

      // Handle events
      $(mDropdownWindow).bind("resize scroll", function () {
        // Hide all dropdowns
        if (Runtime_IsPlatformIOS) {
          // Do not hide since may need to scroll and also, the resize event occurs when the keyboard pops up!
        }
        else {
          for (var i = 0; i < mDropdownWindow.__ISDropdownHandler.length; i++) {
            var dd = mDropdownWindow.__ISDropdownHandler[i];
            if (dd != undefined && dd.CloseOnClickOutside()) {
              if (dd.Visible()) {
                if (dd.AttachedControl && dd.AttachedControl().DropdownHide) {
                  // Let the attached control gracefully hide dropdown
                  dd.AttachedControl().DropdownHide();
                }
                else {
                  // Hide
                  dd.Hide();
                }
              }
            }
          }
        }
      });

      $(mDropdownDocument).bind("click", function (e) {
        // Close if clicked outside dropdown or it's attached element
        for (var i = 0; i < mDropdownWindow.__ISDropdownHandler.length; i++) {
          var dd = mDropdownWindow.__ISDropdownHandler[i];
          if (dd != undefined && dd.CloseOnClickOutside()) {
            if (dd.AttachedElement()[0] === e.target) {
              // Clicked attached element, e.g., a label with a tooltip
            } else if (dd.AttachedElement().has(e.target).length == 0 && dd.Element().has(e.target).length == 0) {
              if (dd.Visible()) {
                if (dd.AttachedControl && dd.AttachedControl().DropdownHide) {
                  // Let the attached control gracefully hide dropdown
                  dd.AttachedControl().DropdownHide();
                }
                else {
                  // Hide
                  dd.Hide();
                }
              }
            }
          }
        }
      });

      $(document).bind("focusout focusin", function (e) {
        // Close if focused outside dropdown or it's attached element
        switch (mDropdownDocument.activeElement.tagName) {
          case "BUTTON":
          case "INPUT":
            for (var i = 0; i < mDropdownWindow.__ISDropdownHandler.length; i++) {
              var dd = mDropdownWindow.__ISDropdownHandler[i];
              if (dd != undefined) {
                if (dd.AttachedElement().has(mDropdownDocument.activeElement).length == 0 && dd.Element().has(mDropdownDocument.activeElement).length == 0) {
                  if (dd.Visible()) {
                    if (dd.AttachedControl && dd.AttachedControl() && dd.AttachedControl().DropdownHide) {
                      // Let the attached control gracefully hide dropdown
                      dd.AttachedControl().DropdownHide();
                    }
                    else {
                      // Hide
                      dd.Hide();
                    }
                  }
                }
              }
            }
            break;
        }
      });
    }
    mDropdownWindow.__ISDropdownHandler.push(_self);


    return _self;
  }



  // -----------------------------------
  // PRIVATE: Style up a file-type Input
  //
  // Version Date: 30-Apr-2024
  // -----------------------------------
  function InputFileInitialise(el) {
    // Supported?
    if (!window.FileReader) return;

    // Already initialised?
    if (el.attr("is-file-upload-initialised")) return;
    el.attr("is-file-upload-initialised", "y");

    // Get properties
    var id = el.attr("id");
    var accept = el.attr("accept");
    var maxFiles = parseInt(el.attr("max-files"));
    if (!maxFiles) maxFiles = 1;
    var maxBytesTotal = 999999; //TODO: attribute

    // Get associated Label
    var elLabel = $("label[for='" + id + "']");
    if (elLabel.length == 0) {
      // Must have an associated Label
      return;
    }

    // Update associated Label
    var elLabel = $("label[for='" + id + "']");
    elLabel.addClass("is-file-upload");
    elLabel.removeClass("is-label-heading");
    var caption = elLabel.text();

    // Replace with a standard TextBox
    var el2 = $("<input id='" + el.attr("id") + "' style='display:none'/>");
    el2.insertAfter(el);
    el.remove();
    el = el2;

    // Give TextBox a GetFiles() method
    // NOTE: The widget.UploadFiles method will check this before attempting to get the built-in 'files' collection
    var files = [];
    el[0].GetFiles = function () {
      return files;
    };
    el[0].GetFileName = function () {
      return files[0].name;
    };

    // Create a list to hold file inputs
    var fileInputs = [];
    for (var i = 0; i < maxFiles; i++) {
      var fi = $("<input type='file' id='" + id + "_" + i + "' style='display:none'/>");
      fi.attr("accept", accept);

      // Rebuild files list on change
      fi.change(function (e) {
        files.length = 0;
        for (var j = 0; j < fileInputs.length; j++) {
          var fi2 = fileInputs[j];
          if (fi2.files.length != 0) {
            files.push(fi2.files[0]);
          }
        }
        el.trigger("change");
      });

      fi.insertAfter(elLabel);
      fileInputs.push(fi[0]);
    }
    
    // Show selected files
    el.change(function (e) {
      elLabel.text("");
      elLabel.children().remove();
      var elc = $("<h1></h1>");
      elc.click(function (e) { e.preventDefault(); });
      elc.html(caption);
      elLabel.append(elc);

      // Preview files
      for (var i = 0; i < files.length; i++) {
        var f = files[i];
        var canPreview = false;

        // Icon
        var icon = "Document";
        var n = f.name.lastIndexOf(".");
        if (n != 0) {
          switch (f.name.substr(n + 1).toUpperCase()) {
            case "BMP":
            case "GIF":
            case "ICO":
            case "JPG":
            case "JPEG":
            case "PNG":
              icon = "Control_Image";
              canPreview = true;
              break;

            case "DOC":
            case "DOCX":
              icon = "DocumentType_Word";
              break;

            case "XLS":
            case "XLSX":
              icon = "DocumentType_Excel";
              break;

            case "PDF":
              icon = "DocumentType_PDF";
              break;
          }
        }

        var fp = $("<div class='preview'></div>");
        var fpi = $("<img src='" + widget.GetIconUrl(icon, 64) + "' width='64'/>");
        fpi.attr("title", f.name);

        if (canPreview) {
          (function (img) {
            var reader = new FileReader();
            reader.onloadend = function () {
              img[0].src = reader.result;
            }
            reader.readAsDataURL(f);
          })(fpi);
        }

        var fpc = $("<label/>");
        var fpr = $("<div><button class='is-button small'>Remove</button></div>");
        (function (index, fileName) {
          $("button", fpr).click(function (e) {
            // Clear first file input that matches file name
            for (var i = 0; i < fileInputs.length; i++) {
              var fi = fileInputs[i];
              if (fi.files.length > 0 && fi.files[0].name == fileName) {
                fi.value = "";
                $(fi).trigger("change");
                break;
              }
            }
          });
        })(i, f.name);
        fpc.text(f.name.length > 25 ? f.name.substr(0, 25) + "..." : f.name);
        fp.append(fpi);
        fp.append(fpc);
        fp.append(fpr);
        elLabel.append(fp);
      }

      // Find spare file input to link to Add button
      var fpa = null;
      for (var i = 0; i < fileInputs.length; i++) {
        var fi = fileInputs[i];

        if (!fi.value) {
          fpa = $("<label class='addfile'><div></div>Add file</label>");
          fpa.attr("for", fi.id);
          break;
        }
      }
      if (!fpa) {
        var s = "";
        if (fileInputs.length == 1) {
          s = "Maximum of <b>1</b> file selected. Remove to choose a different file.";
        }
        else {
          s = "Maximum of <b>" + fileInputs.length + "</b> files selected. Remove to add a different file.";
        }
        fpa = $("<label></label>");
        fpa.html(s);
      }
      elLabel.append(fpa);
    });

    // Rebuild now
    el.trigger("change");
  }



  // ===================
  // PUBLIC: Form object
  // ===================
  function Form(e, options) {
    var mActions;
    var mActionsButton;
    var mActionsElement;
    var mElement;
    var mHeadingElement;
    var mOptions;
    var mSummaryElement;

    // Extend options with defaults
    FormDefaults = {
      cssClass: "is-widget-form",
      captionWidth: "9em",
      style: true,
      textboxWidth: "",
      visible: true,
    };
    mOptions = $.extend({}, FormDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      e = $("#" + e);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      widget.RegisterError("widget_ui.Form: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Get Heading and Summary elements
    mHeadingElement = $("header > div.header", mElement);
    mSummaryElement = $("header > div.summary", mElement);

    // Initialise
    UpdateElement();

    // Visible?
    if (mOptions.visible) {
      mElement.show();
    }
    else {
      mElement.hide();
    }


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      if (mOptions.style && mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // Update all 'is-form' tables
      if (mOptions.style) {
        var tbls = $("table.is-form", mElement);
        for (var i = 0; i < tbls.length; i++) {
          // Get table
          var tbl = $(tbls[i]);

          // If no columns then set automatic width for first column
          var cols = $("col", tbl);
          if (cols.length == 0) {
            tbl.prepend("<colgroup><col style='width:" + mOptions.captionWidth + "'/><col/></colgroup>");
          }

          // Heading labels
          $("th[colspan='2'] > label:first-child,th[colspan='3'] > label:first-child,th[colspan='4'] > label:first-child", tbl).addClass("is-label-heading");
        }
      }

      // Update all controls will a 'data-type' attribute
      var els = $("input,select,textarea", mElement);
      for (var i = 0; i < els.length; i++) {
        // Get control and associated label
        var el = $(els[i]);
        var elLabel = $("label[for='" + el.attr("id") + "']");

        if (el.attr("is-created") == "y") {
          // Already created a 'read' control (e.g., CheckBox) so ignore
        }
        else {
          // Numbers, Dates, Checkboxes etc
          var fieldType = (el.attr("field-type") + "").toUpperCase();
          var inputType = (el.attr("type") + "").toUpperCase();
          var tagName = el.prop("tagName").toUpperCase();


          if (tagName == "SELECT") {
            // ------
            // Select
            // ------
            el.addClass("is-combobox");
          }
          else if (fieldType == "CURRENCY") {
            // --------
            // Currency
            // --------
            if (inputType == "NUMBER") {
              // Cannot do this if type='Number'
              widget.RegisterError("widget_ui.Form: Input '" + el.attr("id") + "' has a field-type of 'Currency' but cannot be handled since it also has a type attribute of 'number'. Remove this attribute if you wish to use Widget number handling.");
            }
            else {
              var blankIfZero = (el.attr("blank-if-zero") == "true");
              if (mOptions.style) el.addClass("is-numberbox");
              el.blur(function () { $(this).val(widget.FormatCurrency(widget.ParseCurrency($(this).val()), false, blankIfZero)); });
              el.focus(function () { $(this).val(widget.ParseCurrency($(this).val())); $(this).select(); });
            }
          }
          else if (fieldType == "INTEGER") {
            // -------
            // Integer
            // -------
            if (inputType == "NUMBER") {
              // Cannot do this if type='Date'
              widget.RegisterError("widget_ui.Form: Input '" + el.attr("id") + "' has a field-type of 'Integer' but cannot be handled since it also has a type attribute of 'number'. Remove this attribute if you wish to use Widget number handling.");
            }
            else {
              var blankIfZero = (el.attr("blank-if-zero") == "true");
              if (mOptions.style) el.addClass("is-numberbox");
              el.blur(function () { $(this).val(widget.FormatNumber(widget.ParseNumber($(this).val(), 0), 0, true, blankIfZero)); });
              el.focus(function () { $(this).val(widget.ParseNumber($(this).val(), 0)); $(this).select(); });
            }
          }
          else if (fieldType == "DATE") {
            // ----
            // Date
            // ----
            if (inputType == "DATE") {
              // Cannot do this if type='Date'
              widget.RegisterError("widget_ui.Form: Input '" + el.attr("id") + "' has a field-type of 'Date' but cannot be handled since it also has a type attribute of 'date'. Remove this attribute if you wish to use Widget date handling.");
            }
            else {
              if (mOptions.style) el.addClass("is-datebox");

              if (!mDisableProxyControls && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
                // Hosted within finCC so hook up to this Date control since it will respect 'side-picker' options
                var d = new window.parent.$UI.DateBox(el, { historic: (el.attr("historic") == "true"), widgetDocument: window.document, usePicker: window.__alwaysUsePickerControls });
              }
              else {
                // External or within finPOWER Connect
                //el.change(function () { $(this).val(widget.FormatDate(widget.ParseDate($(this).val(), ($(this).attr("historic") == "true")))); });
                var d = new DateBox(el, { historic: (el.attr("historic") == "true") });
              }

              // Set placeholder text to show date format
              var pt = el.attr("placeholder");
              if (!pt) el.attr("placeholder", widget.Options.dateFormatTooltip);
            }
          }
          else if (inputType == "FILE") {
            // -----------
            // File Upload
            // -----------
            InputFileInitialise(el);
          }
          else if (inputType == "CHECKBOX") {
            // --------
            // Checkbox
            // --------
            if (mOptions.style) {
              // Convert to our CheckBox control

              // Unwrap first (older HTML Widgets wrapped checkboxes in a span)
              var parent = el.parent();
              var caption = "";
              if (parent.attr("class") == "is-checkbox") {
                caption = $("label", parent).text();
                $("label", parent).remove();
                el.unwrap();
                el.attr("caption", caption);
              }

              // Convert
              var chk = widget.UI.CheckBox(el, { caption: caption });
            }
          }
          else {
            // ----------------------
            // Other (assume Textbox)
            // ----------------------
            switch (el.prop("tagName")) {
              case "SELECT":
                if (mOptions.style) el.addClass("is-combobox");
                break;

              default:
                if (mOptions.style) el.addClass("is-textbox");

                // Default width (unless an inline width is defined)
                if (mOptions.style) {
                  if (el[0].outerHTML.indexOf("width:") == -1) {
                    if (mOptions.textboxWidth) {
                      // Default width is defined
                      el.css("width", "100%");
                      el.css("max-width", mOptions.textboxWidth);
                    }
                    else {
                      // Calculate width from maxlength
                      var maxLength = el.attr("maxlength");
                      if (maxLength) {
                        maxLength = parseInt(maxLength);
                        el.css("width", "100%");
                        el.css("max-width", (maxLength * 0.8) + "em");
                      }
                    }
                  }
                }
                break;
            }
          }

          // Mandatory
          if (el.attr("mandatory")) {
            if (mOptions.style) el.addClass("is-mandatory");

            // Associated Label
            if (mOptions.style) elLabel.addClass("is-mandatory");
          }
        }
      }
    }

    // ----------------------
    // PUBLIC: Define Actions
    // ----------------------
    function ActionsDefine(actions, e, executeActionHandler) {
      // Initialise
      mActions = actions;

      // Get Button Element
      var id;
      if (typeof e == "string") {
        mActionsButton = $("#" + e);
      }
      else {
        mActionsButton = e;
      }

      // Update Button
      mActionsButton.addClass("is-button actions");

      // Show/ Hide button
      if (actions && actions.length > 0) {
        mActionsButton.show();
      }
      else {
        mActionsButton.hide();
      }

      // Create Actions element
      if (!mActionsElement) {
        mActionsElement = $("<div class='is-form-actions-menu' style='display:none'></div>");
        $("body").append(mActionsElement);
      }

      // Handle events
      mActionsButton.unbind("click.actions");
      mActionsButton.bind("click.actions", function () {
        ShowFormActionsMenu(mActionsElement, mActions, executeActionHandler);
      });
    }

    // -------------------------------
    // PRIVATE: Show Form Actions Menu
    // -------------------------------
    function ShowFormActionsMenu(actionsContainerElement, actions, executeActionHandler) {
      var action, button, e, ei, ec, lastGroupId = "", iconUrl;

      // Clear existing
      actionsContainerElement.children().remove();

      // Add menu container and heading
      var container = $("<div class='is-no-select showing' tabindex='-1'></div>");
      actionsContainerElement.append(container);
      var caption = $("<div class='caption'></div>");
      var closeButton = $("<a><span class='is-symbol-close'></span></a>");
      closeButton.click(function () {
        actionsContainerElement.off("click");
        actionsContainerElement.hide();
      });
      caption.append(closeButton);
      container.append(caption);
      var body = $("<div></div>");
      container.append(body);

      // Apply theme information (since Widgets not nothing about finPOWER Connect Cloud theming)
      container.css("border-color", mThemeContrastColourActionsForm);
      caption.css("background-color", mThemeContrastColourActionsForm);

      // Add actions
      var links = $("<ul></ul>");
      var recordGroup = false;
      var visibleCount = 0;
      body.append(links);
      for (var i = 0; i < actions.length; i++) {
        // Initialise
        action = actions[i];

        // Compatibility with finPOWER Connect Cloud userinterface.js code
        if (action.enabled === undefined) action.enabled = true;
        if (action.visible === undefined) action.visible = true;

        // Visible?
        var visible = action.visible;
        if (!visible && action.repeatInGroupId && action.repeatInGroupId.toUpperCase() == "[BUTTONSOTHER]" && action.contextPageId && action.enabled) {
          // This is a page-based Action that is most likely hidden because we're not on the correct page but should still appear in the list
          visible = true;
        }

        if (visible) {
          // Track visible actions
          visibleCount += 1;

          if (action.groupId.substr(0, 1) != "[") {
            // New group?
            if (action.groupId != lastGroupId) {
              lastGroupId = action.groupId;
              recordGroup = (action.groupId == "Record");

              e = $("<li class='heading'></li>");
              e.text(action.groupId);
              if (recordGroup) e.addClass("record-action");
              links.append(e);
            }

            // Action
            e = $("<li class='action'></li>");
            // NOTE: system vs custom is only applicable in finPOWER Connect Cloud
            //if (action.system) {
            //  e.addClass("system");
            //}
            //else {
            //  e.addClass("custom");
            //}
            if (recordGroup) e.addClass("record-action");
            var eb = $("<button></button>");
            e.append(eb);
            if (!action.enabled) {
              e.addClass("disabled");
              eb.attr("disabled", "disabled");
            }
            if (action.icon) {
              ei = $("<img/>");
              eb.append(ei);
              iconUrl = widget.GetIconUrl(action.icon, 16);
              ei.attr("src", iconUrl);
            }
            ec = $("<span></span>");
            if (action.caption.indexOf("<small>") != -1) {
              // Allow limited HTML tags to help clarify actions
              ec.html(action.caption);
            }
            else {
              // Text
              ec.text(action.caption);
            }
            //e.attr("fincc_actionid", action.actionId); // For debugging purposes and for developers wishing to know the Ids of system actions
            //ec.attr("fincc_actionid", action.actionId); // For debugging purposes and for developers wishing to know the Ids of system actions
            eb.append(ec);
            links.append(e);

            // Handler
            if (action.enabled) {
              if (action.handler) {
                // Custom handler
                (function (action) { e.click(function () { actionsContainerElement.hide(); action.handler(); }); })(action);
              }
              else {
                // Default handler
                // NOTE: This will also automatically handle Custom Actions that are Application Shortcuts
                (function (action) { e.click(function () { actionsContainerElement.hide(); executeActionHandler(action.actionId, action.applicationShortcutUrl ? action.applicationShortcutUrl : action.data); }); })(action);
              }
            }
          }
        }
      }

      // Filter textbox?
      if (true) {//visibleCount > 5) {
        var ftb = $("<input type='text' placeholder='Search actions for this record'/>")
        caption.append(ftb);

        ftb.bind("keyup", function (e) {
          switch (e.keyCode) {
            case 27: // Escape
              ftb.val("");
              break;
          }

          // Filter
          FilterElements($("li", links), ftb.val(), true);
        });
      }

      // Show
      actionsContainerElement.show();

      // Handle escape key and clicking background to close
      actionsContainerElement.on("click", function (e) {
        if (e.target === this) {
          closeButton.trigger("click");
        }
      });
      container.bind("keyup", function (e) {
        if (e.keyCode == 27) {
          if (e.target.tagName == "INPUT") {
            // Ignore escape in filter box
          }
          else {
            closeButton.trigger("click");
          }
        }
      });
      container.focus();

      // Focus on filter textbox unless in mobile
      if (!Runtime_IsMobileBrowser && visibleCount > 5) ftb.focus();

      // Remove 'showing' class used for animations
      var ti = window.setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        container.removeClass("showing");
      }, 20);
    }

    // ========================================================
    // PRIVATE: Apply text filter to specified elements=
    //
    // NOTE: No reason this cannot be made PUBLIC at some point
    // ========================================================
    function FilterElements(elements, filterText, showCategoryHeaders) {
      var FILTER_ABBERIVATIONS = [
        { a: "Auto", b: "Account Process" },
        { a: "Autos", b: "Account Process" },
        { a: "DC", b: "Direct Credit" },
        { a: "DD", b: "Direct Debit" },
        { a: "GL", b: "General Ledger" },
      ];

      // Clear all filters
      elements.removeClass("is-filtered-out is-filtered-out-category-visible");

      if (filterText) {
        // Split filter criteria
        var criteria = filterText.toUpperCase().split(" ");

        if (criteria.length > 0) {
          for (var i = 0; i < elements.length; i++) {
            // Get element
            var el = $(elements[i]);

            // Check criteria exists (ALL criteria must exist in an element)
            var foundInRecord = true;
            for (var crit = 0; crit < criteria.length; crit++) {
              var critText = criteria[crit];
              var found = false;
              var elText = el.text();

              if (critText && elText != " ") {
                if (elText && elText.toUpperCase().indexOf(critText) != -1) {
                  found = true;
                }
              }

              // Try abbreviation/ alternatives library, e.g., "GL" for "General Ledger"
              if (!found && critText && elText && elText != " ") {
                for (var fa = 0; fa < FILTER_ABBERIVATIONS.length; fa++) {
                  var ab = FILTER_ABBERIVATIONS[fa];
                  if (ab.a.toUpperCase() == critText || ab.b.toUpperCase == critText) {
                    if (elText.toUpperCase().indexOf(ab.a.toUpperCase()) != -1 || elText.toUpperCase().indexOf(ab.b.toUpperCase()) != -1) {
                      console.log("Element filter matched alternate text " + ab.a + " -> " + ab.b);
                      found = true;
                      break;
                    }
                  }
                }
              }

              if (!found) {
                foundInRecord = false;
                break;
              }
            }

            // Filter out?
            if (!foundInRecord) el.addClass("is-filtered-out");
          }
        }

        // Show category headers (applies to list elements with an H1 above the list or, an LI with a class of heading which, in turn, has an H1 child element)
        if (showCategoryHeaders) {
          if (criteria.length > 0) {
            var lastH1 = null;

            for (var i = 0; i < elements.length; i++) {
              var item = $(elements[i]);

              if (item.prop("tagName") == "H1" || item.hasClass("heading")) {
                // Record last category header
                lastH1 = item;
              }
              else if (item.prop("tagName") == "LI") {
                if (lastH1 && !item.hasClass("is-filtered-out")) {
                  // Show category header since one of its items is not filtered out
                  lastH1.addClass("is-filtered-out-category-visible");
                }
              }
            }
          }
        }
      }
    }

    // ------------------------------
    // PUBLIC: The jQuery DIV Element
    // ------------------------------
    function Element() {
      return mElement;
    }

    // --------------------
    // PUBLIC: Disable Form
    // --------------------
    function FormDisable(message) {
      mFormDisabled = true;

      if (!mFormDisableOverlay) {
        mFormDisableOverlay = $("<div class='is-form-disabled' tabindex='-1' style='position:fixed; left:0; top:0; width:100%; height:100%; z-index:9999999; background-color:black; filter: alpha(opacity=75); opacity:0.75;'>&nbsp;</div>");
        mFormDisableOverlay.blur("", function () { if (mFormDisabled) mFormDisableOverlay.focus(); });
        $("body").append(mFormDisableOverlay);
      }
      mFormDisableOverlay.show(); // Do not use 'fadeIn' since this does not allow automatic focus and therefore double button clicks may register
      mFormDisableOverlay.focus();
    }

    // -------------------
    // PUBLIC: Enable Form
    // -------------------
    function FormEnable() {
      mFormDisabled = false;
      mFormDisableOverlay.hide();
    }

    // ----------------------------
    // PUBLIC: Refresh Form Heading
    // ----------------------------
    function RefreshHeading(heading, summary) {
      if (heading) mHeadingElement.text(heading);
      if (summary) mSummaryElement.text(summary);
    }

    // ------------------------------------
    // PUBLIC: Make form controls read-only
    // ------------------------------------
    function FormReadOnly(controls, readOnly) {
      for (var name in controls) {
        var ctl = controls[name];
        if (ctl && ctl.TypeName && ctl.ReadOnly) {
          // Include?
          var include = true;
          if (ctl.AutoReadOnly && !ctl.AutoReadOnly()) include = false;

          // Update control
          if (include) {
            ctl.ReadOnly(readOnly);
          }
        }
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        if (mOptions.visible) {
          mElement.css("visibility", "visible"); // Forms may be hidden using this method at startup
          mElement.show();
        }
        else {
          mElement.hide();
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "Form",

      Element: Element,

      ActionsDefine: ActionsDefine,

      FormDisable: FormDisable,
      FormEnable: FormEnable,

      FormReadOnly: FormReadOnly,

      RefreshHeading: RefreshHeading,

      Visible: Visible,
    };
    return _self;
  }



  // ===================
  // PUBLIC: Grid object
  // ===================
  function Grid(e, options) {

    var mActions;
    var mActiveDataRowIndex = -1;
    var mActiveColumnIndex = -1;
    var mActiveColumnKey;
    var mAutoHideColumnsTimer;
    var mButtonsElement;
    var mCaptionElement;
    var mCaptionContentElement;
    var mCaptionCloseElement;
    var mCaption = "";
    var mColumns = [];
    var mColumnsDirty = true;
    var mCountHidden = 0;
    var mCustomGroupByOrder = false;
    var mDataRowElements = [];
    var mEditCell;
    var mEditing = false;
    var mEditingDbComboSpecial = false;
    var mEditElement;
    var mEditElementControls;
    var mEditable = false;
    var mEditorInfo;
    var mElement;
    var mElementSelectUnselect;
    var mElementTBody;
    var mHasAutoHideColumns = false;
    var mHiddenRowsVisible = false;
    var mInitialised = false;
    var mInvalidMessageElement;
    var mMenuPopup;
    var mMergedHeadersElement;
    var mNewRowCount = 0;
    var mOptions;
    var mSelectedRowElement;
    var mSelectedRowCountElement;
    var mSorted = false;
    var mStickyFooterElement;
    var mStickyHeaderElement;
    var mStickyHeaderWrapperElement;
    var mStickyHeaderWrapperElement_OldTop = 0;
    var mTableWrapper;
    var mTemplateRow;
    var mVirtualClass;
    var mVirtualData;
    var mWrapperElement;

    var mElementSearch;
    var mTxtSearch;
    var mSearchVisible = false;

    mActions = new ActionsCollection();

    // Grid column defaults
    GridColumnDefaults = {
      key: "",

      align: "",
      allowDrilldown: false,
      blankIfZero: false,
      caption: null,
      customFilterMessage: "",
      drilldownGlyph: null,
      noBreak: false,
      readOnly: false,
      selectable: false,
      sortable: false,
      style: "",
      summary: "",
      tooltipText: "",
      type: "string",
      visible: true,
      width: "",
      minWidth: "",
      wrap: undefined, // true to force a String column to wrap content, even if it contains no white-space
      autoHideBelowScreenWidth: 0, // auto hide this column if the screen width falls below this value

      thElement: null,
      original: false,

      elementCreatedIndex: -1
    };

    // Extend options with defaults
    GridDefaults = {
      cssClass: "is-grid",

      groupByColumns: "",
      groupByDesc: false,           // OBSOLETE: if "true" then groupByOrder will be set to "DESC"
      groupByOrder: "",             // ASC,DESC (blank assumes data is already sorted in the correct order)
      groupingsCollapsed: false,    // Collapse groupings by default (upon performing a VirtualDataRefresh)
      allowGroupingsCollapse: true,
      showGroupCounts: true,

      selectedColumnKey: "",

      showColumnHeaders: true,
      stickyHeader: null, // Default changed to null as of 3.02.01 since we now use position: sticky and want to default based on whether supported or not
      docked: null, // Default based upon sticky header (for compatibility)

      showRowSelectors: false,
      rowNumbering: false,

      allowAddRows: false,
      allowCellSelect: true,
      allowMultiRowSelect: false,

      readOnly: false,
      maxNewRows: 100,
      quickEdit: false,

      sortByColumn: "",
      sortByDesc: false,

      showContextMenu: true,
      showHiddenRowsPopup: true,

      allowSearchBox: true,
      showSearchBox: false,

      style: null, // blank, report, form

      exportFileName: "GridData", // excludes file extension

      visible: true,

      onAction: null,
      onInitialiseRow: null,
      onAfterColumnSort: null,
      onAfterRowActivate: null,
      onBeforeCellEdit: null,
      onBeforeCellUpdate: null,
      onColumnSelect: null,
      onFooterCellFormat: null,
      onRowAdd: null,
      onRowDrilldown: null,
      onSelectedRowsChanged: null,
    };
    mOptions = $.extend({}, GridDefaults, options);
    mSearchVisible = mOptions.allowSearchBox && mOptions.showSearchBox;
    mCustomGroupByOrder = (mOptions.groupByOrder.length != 0);

    // Compatibility
    mOptions.groupByOrder = mOptions.groupByOrder.toUpperCase();
    if (mOptions.groupByDesc && !mOptions.groupByOrder) mOptions.groupByOrder = "DESC";

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      widget.RegisterError("widget_ui.Grid: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Wrap?
    if (mElement.prop("tagName") == "DIV") {
      // <div> supplied
      mElement.addClass("is-grid");
      mWrapperElement = mElement;
      mElement = $("<table><thead class='is-no-select'><tr></tr></thead><tbody></tbody></table>");
      if (mOptions.width) mWrapperElement.css("width", mOptions.width);
      mWrapperElement.append(mElement);
    }
    else {
      // <table> supplied
      mElement.wrap("<div class='is-grid'></div>");
      mWrapperElement = $(mElement.parent());

      // Inherit float CSS from table
      var float = mElement.css("float");
      if (float) mWrapperElement.css("float", float);
    }

    // Sticky header default
    if (mOptions.docked === null) {
      if (mOptions.stickyHeader == true) {
        mOptions.docked = true;
      }
      else {
        mOptions.docked = false;
      }
    }
    if (mOptions.stickyHeader === null) {
      // Default based on whether the browser supports the native CSS to achieve this (IE doesn't!)
      mOptions.stickyHeader = mSupportsStickyHeaders;
    }

    // Allow focus (i.e., so we can handle key presses etc)
    mElement.attr("tabindex", "-1");

    // Wrap table (required for footer caption etc)
    mElement.wrap("<div class='is-grid'></div>");
    mTableWrapper = $(mElement.parent());
    mWrapperElement.addClass("is-grid-container");
    mWrapperElement.removeClass("is-grid");

    // Get existing columns
    var ths = $("thead > tr > th", mElement);
    for (var i = 0; i < ths.length; i++) {
      var th = $(ths[i]);
      var colspan = th.attr("colspan");

      if (colspan) {
        // Ignore colspan columns since these should just be used as a grouping mechanism for the headers below them
        var colspanFor = th.attr("colspan-for");
        if (colspanFor) {
          // Add child columns now (so they are in the correct order)
          var cols = colspanFor.split(",");
          for (var j = 0; j < cols.length; j++) {
            var th2 = $("th[key='" + cols[j] + "']", mElement);
            if (th2.length > 0) {
              AddColumnFromTh($(th2[0]));
            }
            else {
              console.warn("widget.UI.Grid: colspan-for '" + cols[j] + "', child column not found");
            }
          }
        }
      }
      else {
        // Add column
        AddColumnFromTh(th);
      }
    }

    // Handle events
    mElement.bind("keyup", function (e) {
      if (mEditing) return;

      switch (e.keyCode) {
        case 13: // Enter
          if (mEditable) {
            EditorEnterEditMode();

            return false;
          }
          break;
      }
    });
    mElement.bind("keydown", function (e) {
      if (mEditing) return;

      switch (e.keyCode) {
        case 9: // Tab
          if (mOptions.allowCellSelect) {
            if (e.shiftKey) {
              ActiveColumnPrevious();
            }
            else {
              ActiveColumnNext();
            }
            return false;
          }
          break;

        case 13: // Enter
          //if (mVirtualData && mActiveDataRowIndex >= 0 && mActiveDataRowIndex < mVirtualData.length) PerformRowDrilldown(mActiveDataRowIndex, "");
          break;

        case 27: // Escape
          ActiveDataRowIndex(-1);
          ActiveColumnIndex(-1);
          break;

        case 32: // Space
          // Toggle editable boolean column
          if (mEditable && !mOptions.readOnly && mActiveDataRowIndex != -1 && mActiveColumnIndex != -1) {
            var col = mColumns[mActiveColumnIndex];
            if (col.type == "Boolean" && col.allowEdit) {
              var cb = $("td.is-sel > input.is-grid-checkbox", mElement);
              cb.trigger("click");
              return false;
            }
          }
          break;

        case 35: // End
          if (mVirtualData) {
            ActiveDataRowIndex(mVirtualData.length - 1);

            // Scroll into view
            ActiveDataRowScrollIntoView();
          }
          return false; // Prevent default key action

        case 36: // Home
          if (mVirtualData) {
            ActiveDataRowIndex(0);

            // Scroll into view
            ActiveDataRowScrollIntoView();
          }
          return false; // Prevent default key action

        case 33: // Page Up
          ActiveDataRowPageUp();
          return false; // Prevent default key action

        case 34: // Page Down
          ActiveDataRowPageDown();
          return false; // Prevent default key action

        case 37: // Cursor Left
          ActiveColumnPrevious();
          return false; // Prevent default key action

        case 38: // Cursor Up
          ActiveDataRowPrevious();
          return false; // Prevent default key action

        case 39: // Cursor Right
          ActiveColumnNext();
          return false; // Prevent default key action

        case 40: // Cursor Down
          if (mVirtualClass && mActiveDataRowIndex == mVirtualClass.length - 1 && mOptions.allowAddRows && !mOptions.readOnly) {
            // Add Row
            var row = mVirtualData[mActiveDataRowIndex];
            if (row.newRow) {
              // Hasn't been edited yet so prevent cursor down from adding multiple new rows
            }
            else {
              AddRow(true);
            }
          }
          else {
            ActiveDataRowNext();
          }
          return false; // Prevent default key action

        case 46: // Delete
          if (mEditable && mActiveColumnIndex == -1 && mActiveDataRowIndex != -1) {
            // Delete Row
            if (mOptions.onAction) mOptions.onAction("DeleteRow");
          }
          else {
            // Enter Edit Mode (and therefore delete cell content)
            switch (mColumns[mActiveColumnIndex].type) {
              case "Currency":
              case "Double":
              case "Integer":
                // Clear number
                // NOTE: For some reason the number box swallows the delete key!
                PerformBeforeCellUpdate(mActiveDataRowIndex, mActiveColumnKey, null, true);
                break;

              default:
                EditorEnterEditMode();
                var ti = window.setTimeout(function () {
                  window.clearTimeout(ti);
                  ti = null;

                  EditorExitEditMode(false);
                }, 10);
            }
          }
          break;

        case 113: // F2
          if (mEditable) {
            EditorEnterEditMode();
          }
          break;

        default:
          if (mEditable) {
            if ((e.keyCode >= 32 && e.keyCode <= 111) || e.keyCode == 189) { // 189 = minus on normal keyboard
              // Alpha-numeric to enter edit mode
              EditorEnterEditMode();
            }
            else {
              switch (e.keyCode) {
                case 187: // Equals
                case 191: // Question Mark
                  EditorEnterEditMode();
                  break;
              }
            }
          }
          break;
      }
    });
    $(window).on("resize", function () {
      // Cancel timer
      if (mAutoHideColumnsTimer) {
        window.clearTimeout(mAutoHideColumnsTimer);
        mAutoHideColumnsTimer = null;
      }

      if (mHasAutoHideColumns) {
        // Defer slightly
        mAutoHideColumnsTimer = window.setTimeout(UpdateAutoHideColumns, 500);
      }
    });

    // Initialise
    if (mColumns.length == 0) {
      // Do nothing if no columns since the Refresh method should be called after adding columns etc
    }
    else {
      UpdateElement(true);
    }

    // ---------------------------------------
    // Update Auto-Hide columns (after resize) 
    // ---------------------------------------
    function UpdateAutoHideColumns() {
      // Check
      if (!mHasAutoHideColumns) return;

      // Quick visibility test
      if (!mOptions.visible) return;

      // Initialise
      var screenWidth = window.innerWidth;

      // Update table cells
      $("tr>td,tr>th", mElement).removeClass("cellhidden");
      for (var j = 0; j < mColumns.length; j++) {
        // Initialise
        var c = mColumns[j];
        var offset = mOptions.rowNumbering || mOptions.allowMultiRowSelect || mOptions.showRowSelectors ? 1 : 0;

        // Hide Column?
        if (c.elementCreatedIndex !== -1 && c.autoHideBelowScreenWidth > 0 && screenWidth <= c.autoHideBelowScreenWidth) {
          $("tr>td:nth-child(" + (offset + c.elementCreatedIndex + 1) + "),tr>th:nth-child(" + (offset + c.elementCreatedIndex + 1) + ")", mElement).addClass("cellhidden");
        }
      }
    }

    // ------------------------------------------------------
    // Add a column from an existing (HTML-defined TH) column
    // ------------------------------------------------------
    function AddColumnFromTh(th) {
      // Check th not already handled (e.g., added as part of a colspan)
      if (th.attr("_original")) return;

      th.attr("_original", "true"); // Flag as being an original column
      var key = th.attr("key") || th.attr("fieldId") || "Column" + i;
      var col = {
        key: key,
        thElement: th,
        original: true,

        align: th[0].style.textAlign,
        allowEdit: th.attr("allow-edit") == "true",
        caption: th.attr("caption"),
        drilldownGlyph: th.attr("drilldown-glyph"),
        selectable: th.attr("selectable") == "true",
        sortable: th.attr("sortable") == "true",
        summary: th.attr("summary"),
        type: th.attr("data-type") || "string",
        visible: th.attr("visible") != "false",
        width: th[0].style.width,
      };

      // Get Caption
      if (!col.caption) col.caption = th.text();

      mColumns.push(col);
    }

    // --------------------------------
    // PUBLIC: Clear Columns Collection
    // --------------------------------
    function ClearColumns() {
      // Remove dynamically create column headers
      if (mColumns) {
        for (var i = 0; i < mColumns.length; i++) {
          var col = mColumns[i];
          if (col.thElement && !col.original) {
            col.thElement.remove();
          }
        }
      }

      // Clear collection
      mColumns = [];
    }

    // ----------------------------------------
    // PUBLIC: Get a Column definition by index
    // ----------------------------------------
    function GetColumnByIndex(index) {
      if (index >= 0 && index < mColumns.length) {
        return mColumns[index];
      }

      return null;
    }

    // --------------------------------------
    // PUBLIC: Get a Column definition by key
    // --------------------------------------
    function GetColumnByKey(key) {
      if (!key) return null;

      key = key.toUpperCase();

      for (var i = 0; i < mColumns.length; i++) {
        if (key == mColumns[i].key.toUpperCase()) {
          return mColumns[i];
        }
      }

      return null;
    }

    // -------------------------------------------
    // PRIVATE: Get a Column definition by caption
    // -------------------------------------------
    function GetColumnByCaption(caption) {
      if (!caption) return null;

      caption = caption.toUpperCase();

      for (var i = 0; i < mColumns.length; i++) {
        if (caption == mColumns[i].caption.toUpperCase()) {
          return mColumns[i];
        }
      }

      return null;
    }

    // ----------------------------------
    // PRIVATE: Get a Column index by key
    // ----------------------------------
    function GetColumnIndexFromKey(key) {
      key = key.toUpperCase();

      for (var i = 0; i < mColumns.length; i++) {
        if (key == mColumns[i].key.toUpperCase()) {
          return i;
        }
      }

      return -1;
    }

    // --------------------------
    // PUBLIC: Add Boolean Column
    // --------------------------
    function AddColumnBoolean(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "Boolean";
      if (!c.width) c.width = "1em";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // -------------------------------
    // PUBLIC: Add Colour Block Column
    // -------------------------------
    function AddColumnColourBlock(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "ColourBlock";
      if (!c.width) c.width = "16px";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // ------------------------------
    // PUBLIC: Add Colour Flag Column
    // ------------------------------
    function AddColumnColourFlag(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "ColourFlag";
      if (!c.width) c.width = "16px";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // ---------------------------
    // PUBLIC: Add Currency Column
    // ---------------------------
    function AddColumnCurrency(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "Currency";
      if (!c.width) c.width = "4em";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // -----------------------
    // PUBLIC: Add Date Column
    // -----------------------
    function AddColumnDate(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "Date";
      if (!c.width) c.width = "4em";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // ----------------------------
    // PUBLIC: Add Date/Time Column
    // ----------------------------
    function AddColumnDateTime(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "DateTime";
      if (!c.width) c.width = "6em";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // -------------------------
    // PUBLIC: Add Double Column
    // -------------------------
    function AddColumnDouble(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "Double";
      if (!c.decimals) c.decimals = 0;
      if (!c.width) c.width = "8em";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // ----------------------------
    // PUBLIC: Add Drilldown Column
    // ----------------------------
    function AddColumnDrilldown(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      if (!key) key = "Drilldown";
      c.key = key;

      // Defaults
      c.type = "Drilldown";
      c.width = "20px";
      c.allowDrilldown = true;

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // -----------------------
    // PUBLIC: Add HTML Column
    // -----------------------
    function AddColumnHtml(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "HTML";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // -----------------------
    // PUBLIC: Add Icon Column
    // -----------------------
    function AddColumnIcon(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "Icon";
      if (!c.width) c.width = "16px";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // --------------------------
    // PUBLIC: Add Integer Column
    // --------------------------
    function AddColumnInteger(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "Integer";
      if (!c.width) c.width = "4em";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // -------------------------
    // PUBLIC: Add String Column
    // -------------------------
    function AddColumnString(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "String";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;

      if (c.collection) {
        // Collection
        c._collection = {};
        c._collection.data = c.collection;
        c._collection.idColumn = c.idColumn;
        c._collection.displayColumns = c.columns;
      }
      else if (c.list) {
        // Must pre-load any resolvable list into a collection so it is available (hopefully), as soon as the user tries to drop the list down
        ColumnFetchList(c);
      }
    }

    // ------------------------------
    // PRIVATE: Fetch a Column's List
    // ------------------------------
    function ColumnFetchList(c) {
      // Initialise
      if (!c._collection) c._collection = {};

      // Cached?
      var cacheKey = c.list + "|" + c.idColumn + "|" + c.displayColumns;

      // From Cache?
      if (mGridListCache[cacheKey]) {
        var record = mGridListCache[cacheKey];

        // Update Collection
        c._collection.data = record.data;
        c._collection.idColumn = record.idColumn;
        c._collection.displayColumns = record.displayColumns;
        c._collection.loaded = true;
        return;
      }

      // Clear existing
      c._collection = {};
      c._collection.loaded = false;
      c._collection.data = [{ "List not loaded": "" }];
      c._collection.idColumn = "List not loaded";

      // Fetch collection
      widget._SystemGetString("ResolveList", { list: c.list, columns: c.columns, idColumn: c.idColumn },
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Get display columns
          var displayColumns = "";
          for (var i = 0; i < data.Columns.length; i++) {
            if (data.Columns[i].Name == data.IdColumn) {
              // Skip Id Column
            }
            else {
              if (displayColumns) displayColumns += ",";
              displayColumns += data.Columns[i].Name;
            }
          }

          // Convert Rows array into an array of objects
          // NOTE: Transferring an array of values is more compact than an array of objects!
          var newRows = [];
          for (var i = 0; i < data.Rows.length; i++) {
            var row = {};
            var item = data.Rows[i];

            for (var j = 0; j < data.Columns.length; j++) {
              row[data.Columns[j].Name] = item[j];
            }

            newRows.push(row);
          }

          // Update Collection
          c._collection.data = newRows;
          c._collection.idColumn = data.IdColumn;
          c._collection.displayColumns = displayColumns;
          c._collection.loaded = true;

          // Cache
          mGridListCache[cacheKey] = {
            data: newRows,
            idColumn: data.IdColumn,
            displayColumns: displayColumns,
          };
        },

        function (data) {
          widget.RegisterError("widget_ui.Grid: Failed to resolve list: " + c.list);
        });
    }

    // ----------------------------------------------------------------------------------
    // PUBLIC: Add Code Column (same as String but hyperlinks will be styled differently)
    // ----------------------------------------------------------------------------------
    function AddColumnCode(key, options) {
      // Initialise
      var c = $.extend({}, GridColumnDefaults, options);
      c.key = key;

      // Defaults
      c.type = "Code";

      // Add
      mColumns.push(c);

      // Dirty
      mColumnsDirty = true;
    }

    // -----------------------------------------------------------------
    // PUBLIC: Add a Column from a finTaskManager2UserDataHeading object
    // -----------------------------------------------------------------
    function AddColumnFromTaskManager2UserDataHeading(heading) {
      // NOTE: Invisible columns are still added since they may be required for Data Export purposes
      switch (heading.DataType) {
        case "Boolean":
          AddColumnBoolean("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, sortable: true });
          break;

        case "Code":
          AddColumnCode("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, sortable: true });
          break;

        case "Currency":
          AddColumnCurrency("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, showSeparators: heading.ShowSeparators, sortable: true });
          break;

        case "Date":
          AddColumnDate("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, sortable: true });
          break;

        case "DateTime":
          AddColumnDateTime("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, sortable: true });
          break;

        case "Double":
          AddColumnDouble("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, decimals: heading.DecimalPlaces, showSeparators: heading.ShowSeparators, sortable: true });
          break;

        case "Html":
          AddColumnHtml("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, sortable: true });
          break;

        case "Icon":
          AddColumnIcon("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, sortable: true });
          break;

        case "Integer":
          AddColumnInteger("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, showSeparators: heading.ShowSeparators, sortable: true });
          break;

        case "String":
          AddColumnString("UserData" + heading.Index, { taskManager2UserDataHeading: heading, caption: heading.Caption, minWidth: heading.WidthHtml, visible: heading.Visible, sortable: true });
          break;

        default:
          console.warn("widget_ui.Grid: Unhandled Task Manager 2 User Data Heading Data Type '" + heading.DataType + "'.");
      }
    }

    // -----------------------------
    // PUBLIC: Column Count property
    // -----------------------------
    function ColumnCount() {
      return mColumns.length;
    }

    // ------------------------------------------------------------------------------
    // PUBLIC: Sort Columns via an array containing their keys and hide other columns
    // ------------------------------------------------------------------------------
    function SortColumnsByArray(arr, matchOnCaption, removeAutoHideProperties) {
      if (!matchOnCaption) matchOnCaption = false; else matchOnCaption = true;
      if (!removeAutoHideProperties) removeAutoHideProperties = false; else removeAutoHideProperties = true;

      // Just in case!
      if (!arr || arr.length == 0) return;

      // Initialise columns
      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];

        // Hide
        c.visible = false;

        // Remove auto-hide properties?
        if (removeAutoHideProperties) {
          c.autoHideBelowScreenWidth = 0;
        }
      }

      // Create a new array of columns in the correct order
      var arrColumns = [];
      if (arr && arr.length != 0) {
        for (var i = 0; i < arr.length; i++) {
          var key = arr[i];
          var col;
          if (matchOnCaption) {
            col = GetColumnByCaption(key);
          }
          else {
            col = GetColumnByKey(key);
          }

          if (col) {
            arrColumns.push(col);
            col.visible = true;
          }
          else {
            if (matchOnCaption) {
              console.warn("widget.UI.Grid.SortColumnsByArray: Array contains invalid column caption '" + key + "'.");
            }
            else {
              console.warn("widget.UI.Grid.SortColumnsByArray: Array contains invalid column key '" + key + "'.");
            }
          }
        }
      }

      // Add in any columns not specified (these will still be invisible)
      for (var i = 0; i < mColumns.length; i++) {
        var col = mColumns[i];
        if (!arrColumns.includes(col)) {
          arrColumns.push(col);
        }
      }

      // Replace array
      mColumns = arrColumns;
    }

    // ---------------------------------------------------------------------------------
    // PUBLIC: Merge column headers (i.e., add a colspan) providing headers are adjacent
    // ---------------------------------------------------------------------------------
    function MergeColumnHeaders(keysCsvList, caption) {
      var keys = keysCsvList.toUpperCase().split(",");

      // Merge
      var firstInListIndex = -1;
      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];

        // Check in list
        var inList = false;
        for (var j = 0; j < keys.length; j++) {
          if (c.key.toUpperCase() == keys[j]) {
            inList = true;
            if (firstInListIndex == -1) firstInListIndex = i;
            break;
          }
        }

        // Merge
        if (!inList || i == mColumns.length - 1) {
          if (firstInListIndex != -1 || (inList && i == mColumns.length - 1)) {
            // Create merge row?
            if (!mMergedHeadersElement) {
              mMergedHeadersElement = $("<tr></tr>");
              $("thead", mElement).prepend(mMergedHeadersElement);
            }

            // Add cell
            var td = $("<th style='text-align:center'></th>");
            td.text(caption);
            td.attr("colspan", i - firstInListIndex);
            mMergedHeadersElement.append(td);

            mColumns[firstInListIndex].thElementMerged = td;
            for (var j = firstInListIndex; j < i; j++) {
              mColumns[j].merged = true;
            }

            // Handle last column
            if (inList && i == mColumns.length - 1) {
              mColumns[i].merged = true;
              if (firstInListIndex != -1) td.attr("colspan", i - firstInListIndex + 1);
            }
          }

          // Reset
          firstInListIndex = -1;
        }
      }

      // Dirty
      mColumnsDirty = true;
    }

    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement(initialise, afterSort) {
      afterSort = afterSort || false;
      var LastGroup = null;

      // Redoing hidden rows if NOT sorting
      if (!afterSort) mCountHidden = 0;

      // Initialise (i.e., create/ initialise elements)?
      if (initialise || !mInitialised) {
        // Flags
        mHasAutoHideColumns = false;
        mInitialised = true;

        // Wrapper Element
        if (mOptions.docked) {
          mWrapperElement.addClass("docked");
        }
        else {
          mWrapperElement.removeClass("docked");
        }
        if (mOptions.stickyHeader) {
          if (mSupportsStickyHeaders) {
            mWrapperElement.addClass("is-sticky-header");
          }
          else {
            mWrapperElement.addClass("is-legacy-sticky-header");
          }
        }
        else {
          mWrapperElement.removeClass("is-sticky-header");
          mWrapperElement.removeClass("is-legacy-sticky-header");
        }

        // Create Search
        if (mOptions.allowSearchBox && !mElementSearch) {
          // Container
          mElementSearch = $("<div class='is-grid-search'><input type='search' style=''/></div>");
          mWrapperElement.prepend(mElementSearch);

          // Create Table Filter
          mTxtSearch = widget.UI.TableFilterTextBox($("input", mElementSearch), {
            allowBlank: true,
            blankTip: mOptions.customFilterMessage,
            maxLength: 100,

            onFilterApplied: function () {
              if (mTxtSearch.Text() == "") {
                // Scroll into view
                ActiveDataRowScrollIntoView();
              }
            }
          });

          // Hide?
          if (!mSearchVisible) mElementSearch.addClass("hidden");
        }

        // Main Element
        mElement.addClass(mOptions.cssClass);
        if (mOptions.style) {
          mElement.addClass(mOptions.style);
          mWrapperElement.addClass(mOptions.style);

          switch (mOptions.style.toUpperCase()) {
            case "FORM":
            case "REPORT":
              break;

            default:
              console.warn("widget.UI.Grid: Invalid grid style '" + mOptions.style + "'. Supported styles are: form, report");
              break;
          }
        }

        // Create Invalid Message element
        if (!mInvalidMessageElement) {
          mInvalidMessageElement = $("<div class='is-grid-caption invalid'><span>xxxxx</span></div>");
          mWrapperElement.append(mInvalidMessageElement);
        }
        mInvalidMessageElement.hide();

        // Create caption (for displaying hidden rows message)
        if (!mCaptionElement) {
          mCaptionElement = $("<div class='is-grid-caption'><span></span><div class='close is-symbol-close'></div></div>");
          mCaptionContentElement = $("span", mCaptionElement);
          mCaptionContentElement.text(mCaption);
          mCaptionCloseElement = $(".close", mCaptionElement);
          mWrapperElement.append(mCaptionElement);

          // Handle caption events
          mCaptionCloseElement.on("click", function (e) { mCaptionElement.slideUp("fast"); e.stopPropagation(); });
          mCaptionElement.on("click", function () { ShowHiddenRows(true); });
        }

        // Create buttons element (for button strip below grid)
        // NOTE: Unlike the finCC grid, buttons may also be defined in a <tfoot> element, this should NOT be used in conjunction with the grid buttons
        if (!mButtonsElement) {
          mButtonsElement = $("<div class='is-grid-buttons'></div>");
          mWrapperElement.append(mButtonsElement);
        }

        // Get/ Create heading row
        var thead = $("thead > tr", mElement);
        if (thead.length > 1) thead = $(thead[thead.length - 1]); // Just in case a merged header row exists
        if (thead.length == 0) {
          var eth = $("<thead></thead>");
          thead = $("<tr></tr>");
          eth.append(thead);
          mElement.append(eth);
        }

        if ((mOptions.rowNumbering || mOptions.allowMultiRowSelect || mOptions.showRowSelectors) && !mElementSelectUnselect && $("th.rowselector", thead).length == 0) {
          var th = $("<th class='rowselector'></th>");
          thead.prepend(th);  // Prepend just in case existing columns are defined in HTML

          // Select all/ none button
          if (mOptions.allowMultiRowSelect) {
            // See also sticky header code in UpdateElement
            var chk = $("<input type='checkbox'/>");
            th.append(chk);
            mElementSelectUnselect = new widget.UI.CheckBox(chk, {
              onChange: function (sender, e) {
                SelectAllRows(sender.Value(), true);
              }
            });

            // Selected Row Count label
            if (!mSelectedRowCountElement) {
              mSelectedRowCountElement = $("<div style='border:1px solid rgba(0, 0, 0, 0.1); background-color:#ffffee; padding:4px; font-size:10px; position:fixed; display:none; color:navy; line-height:10px; left:20px; cursor:pointer; z-index:9999'></div>");
              mSelectedRowCountElement.click(function () {
                SelectAllRows(false, false);
              });
              mTableWrapper.prepend(mSelectedRowCountElement);
            }
          }
        }

        // Initialise Editing functionality
        mEditable = false;
        mEditing = false;
        mEditingDbComboSpecial = false;
        if (!mEditElement) {
          // Container
          mEditElement = $("<div style='display:none; position:absolute;' class='grid-cell-editor'></div>");

          mEditElement.off("focusout");
          mEditElement.on("focusout", function (e) {
            // Exit edit mode
            if (mEditing) {
              if (mEditElementControls.listbox.Visible()) {
                // ComboBox
                // Do not exit edit mode since this is done in the change event to avoid dropdown closing too soon
              }
              else if (mEditElementControls.dbcombo.Visible()) {
                // DBCombo
                // Do not exit edit mode since this is done in the change event to avoid dropdown closing too soon
              }
              else {
                // Other
                EditorExitEditMode(false);
              }
            }
          });

          // Add immediately
          // NOTE: If this is not done then adding the ComboBox will immediately remove it's dropdown since it is not in the DOM!
          mTableWrapper.append(mEditElement);

          // Editor controls
          var ec;
          mEditElementControls = {};

          // TextBox
          ec = $("<input/>");
          mEditElement.append(ec);
          mEditElementControls.textbox = widget.UI.TextBox(ec, {
            onChange: function () { EditorExitEditMode(false); },
          });
          mEditElementControls.textbox.Element().css({ "background-color": "white", position: "absolute", left: 0, top: 0, right: 0, bottom: 0, width: "100%", height: "100%" });
          mEditElementControls.textbox.Element().on("keydown", function (e) {
            switch (e.keyCode) {
              case 9:
                if (e.shiftKey) {
                  EditorExitEditMode(false);
                  ActiveColumnPrevious();
                }
                else {
                  EditorExitEditMode(false);
                  ActiveColumnNext();
                }
                return false;
            }
          });
          mEditElementControls.textbox.Element().on("keyup", function (e) {
            switch (e.keyCode) {
              case 13:
                EditorExitEditMode(false);
                return false;

              case 27:
                EditorExitEditMode(true);
                return false;

              case 38:
                EditorExitEditMode(false);
                ActiveDataRowPrevious();
                return false;

              case 40:
                EditorExitEditMode(false);
                ActiveDataRowNext(true);
                return false;
            }
          });

          // ListBox
          // NOTE: Use textarea instead of input to handle wrapping content
          //ec = $("<input/>");
          ec = $("<textarea class='is-textbox' style='resize:none; overflow-y:hidden'/>");
          mEditElement.append(ec);
          mEditElementControls.listbox = widget.UI.ComboBox(ec, {
            forceWidgetControl: true, // Just in case things get incompatible with finCC controls
            createdForGrid: true,

            width: "100%",


            //onChange: function (sender, e) {
            //  if (e && e.ChangedFromPopup) {
            //    EditorExitEditMode(false);
            //  }
            //},

            onAfterDropdownClosed: function (sender, e) {
              EditorExitEditMode(false);
            },
          });
          //mEditElementControls.listbox.Element().css({ "background-color": "white" });
          mEditElementControls.listbox.Element().on("keydown", function (e) {
            switch (e.keyCode) {
              case 9:
                if (e.shiftKey) {
                  EditorExitEditMode(false);
                  ActiveColumnPrevious();
                }
                else {
                  EditorExitEditMode(false);
                  ActiveColumnNext();
                }
                return false;
            }
          });
          mEditElementControls.listbox.Element().on("keyup", function (e) {
            switch (e.keyCode) {
              case 13:
                EditorExitEditMode(false);
                return false;

              case 27:
                EditorExitEditMode(true);
                return false;
            }
          });

          // CheckList
          ec = $("<div></div>");
          mEditElement.append(ec);
          mEditElementControls.checklist = widget.UI.CheckList(ec, {
            forceWidgetControl: true, // Just in case things get incompatible with finCC controls
            createdForGrid: true,

            width: "100%",
          });
          mEditElementControls.checklist.WrapperElement().css("box-shadow", "1px 2px 4px 2px rgba(0, 0, 0, 0.2)");
          mEditElementControls.checklist.WrapperElement().css("animation", "pop-full 0.1s");
          mEditElementControls.checklist.WrapperElement().on("keydown", function (e) {
            switch (e.keyCode) {
              case 9:
                if (e.shiftKey) {
                  EditorExitEditMode(false);
                  ActiveColumnPrevious();
                }
                else {
                  EditorExitEditMode(false);
                  ActiveColumnNext();
                }
                return false;

              case 27:
                EditorExitEditMode(true);
                return false;
            }
          });
          mEditElementControls.checklist.WrapperElement().on("keyup", function (e) {
            switch (e.keyCode) {
              case 13:
                EditorExitEditMode(false);
                return false;
            }
          });

          // DBCombo
          // NOTE: Use textarea instead of input to handle wrapping content
          //ec = $("<input/>");
          ec = $("<textarea class='is-textbox' style='resize:none; overflow-y:hidden'/>");
          mEditElement.append(ec);
          mEditElementControls.dbcombo = widget.UI.DBCombo(ec, {
            forceWidgetControl: true, // Just in case things get incompatible with finCC controls
            createdForGrid: true,

            showDescription: false,

            width: "100%",

            onChange: function (sender, e) {
              //if (e && e.ChangedFromPopup) {
              if (e && e.ChangedFromPopupClick) {
                EditorExitEditMode(false);
              }
            }
          });
          mEditElementControls.dbcombo.Element().on("keydown", function (e) {
            switch (e.keyCode) {
              case 9:
                if (e.shiftKey) {
                  EditorExitEditMode(false);
                  ActiveColumnPrevious();
                }
                else {
                  EditorExitEditMode(false);
                  ActiveColumnNext();
                }
                return false;
            }
          });
          mEditElementControls.dbcombo.Element().on("keyup", function (e) {
            switch (e.keyCode) {
              case 13:
                EditorExitEditMode(false);
                return false;

              case 27:
                EditorExitEditMode(true);
                return false;
            }
          });

          // NumberBox
          ec = $("<input/>");
          mEditElement.append(ec);
          mEditElementControls.numberbox = widget.UI.NumberBox(ec, {
            onChange: function () { EditorExitEditMode(false); },
          });
          mEditElementControls.numberbox.Element().css({ "background-color": "white" });
          mEditElementControls.numberbox.Element().on("keydown", function (e) {
            switch (e.keyCode) {
              case 9:
                if (e.shiftKey) {
                  EditorExitEditMode(false);
                  ActiveColumnPrevious();
                }
                else {
                  EditorExitEditMode(false);
                  ActiveColumnNext();
                }
                return false;
            }
          });
          mEditElementControls.numberbox.Element().on("keyup", function (e) {
            switch (e.keyCode) {
              case 13:
                EditorExitEditMode(false);
                return false;

              case 27:
                EditorExitEditMode(true);
                return false;

              case 38:
                EditorExitEditMode(false);
                ActiveDataRowPrevious();
                return false;

              case 40:
                EditorExitEditMode(false);
                ActiveDataRowNext(true);
                return false;
            }
          });
        }

        // Update classes etc
        if (mOptions.allowAddRows && !mOptions.readOnly) {
          mWrapperElement.addClass("has-add-row");
        }
        else {
          mWrapperElement.removeClass("has-add-row");
        }

        // Add/ Update Column Headings
        // NOTE: Create regardless of whether column headers are being shown
        for (var i = 0; i < mColumns.length; i++) {
          // Get Column
          var col = mColumns[i];

          // Initialise
          col.elementCreatedIndex = i;

          // Editable?
          if (col.allowEdit) mEditable = true;

          // Has auto-hide columns?
          if (col.autoHideBelowScreenWidth > 0) mHasAutoHideColumns = true;

          // Add Heading?
          if (!col.thElement) {
            // Create
            var h = $("<th></th>");
            h.attr("key", col.key);
            thead.append(h);
            col.thElement = h;

            // Update
            if (col.captionIcon) {
              // Icon
              h.html("<img src='" + widget.GetIconUrl(col.captionIcon, 16) + "' style='vertical-align:middle'/>");
              if (col.caption) $("img", h).attr("title", col.caption);
            }
            else if (!col.caption) {
              // No caption
              h.addClass("nocaption");
            }
            else if (col.caption.substr(0, 6).toUpperCase() == "<HTML>") {
              h.html(col.caption.substr(6));
            }
            else {
              h.text(col.caption);
            }
            if (col.width) {
              h.css("width", col.width);
            }
            if (col.minWidth) {
              h.css("min-width", col.minWidth);
            }
            h.addClass("is-grid-col-" + col.type.toLowerCase());
            if (col.autoHideWidth != 0) mHasAutoHideColumns = true;
            if (col.align) h.css("text-align", col.align);

            // Add
            thead.append(h);
          }
          if (!mOptions.showColumnHeaders) {
            thead.hide();
          }

          // Format
          FormatColumnCell(col, col.thElement, "th");

          // Initialise
          col.thElement.off("click");
          col.thElement.removeClass("sortable selectable");

          // Selectable?
          if (col.selectable) {
            col.thElement.addClass("selectable");

            (function (col) {
              col.thElement.click(function () {
                SelectedColumnKey(col.key);
              });
            })(col);
          }

          // Sortable?
          if (col.sortable) {
            col.thElement.addClass("sortable");

            // Add sorter button
            if (!col.sorterElement) {
              col.sorterElement = $("<div class='sorter'></div>");
              col.thElement.append(col.sorterElement);

              (function (col) {
                col.sorterElement.click(function (e) {
                  Sort(col.key);
                  e.preventDefault();
                  return false;
                });
              })(col);
            }
          }
        }

        // Sort out merged header cells into the correct rows
        if (mMergedHeadersElement) {
          var headerRow = $("thead > tr:last-child", mElement);

          // Ensure row selector header spans rows and is in the top row
          var rsh = $("th.rowselector", headerRow);
          if (rsh.length != 0) {
            rsh.attr("rowspan", 2);
            if ($("th.rowselector", mMergedHeadersElement).length == 0) {
              mMergedHeadersElement.prepend(rsh);
            }
          }

          for (var i = 0; i < mColumns.length; i++) {
            var c = mColumns[i];
            if (c.thElementMerged) {
              // Merged header must go in the top row
              mMergedHeadersElement.append(c.thElementMerged);
              headerRow.append(c.thElement);
            }
            else if (c.merged) {
              // Merged cells must go underneath
              headerRow.append(c.thElement);
            }
            else {
              // Non-merged cells must go in top row
              c.thElement.attr("rowspan", 2);
              mMergedHeadersElement.append(c.thElement);
            }
          }
        }

        // Get/ Create TBODY
        mElementTBody = $("tbody", mElement);
        if (mElementTBody.length == 0) {
          mElementTBody = $("<tbody></tbody");
          mElement.append(mElementTBody);
        }
      }

      // Column Headers
      var ths = $("thead > tr > th", mElement);
      ths.removeClass("sorted sorted-desc selected");

      // Sorting styles
      if (mOptions.sortByColumn) {
        var e = $("thead > tr > th[key='" + mOptions.sortByColumn + "']", mElement);
        e.addClass("sorted");
        if (mOptions.sortByDesc) e.addClass("sorted-desc");
      }

      // Clear stored elements
      mDataRowElements = [];

      // Clear data rows
      mSelectedRowElement = null;
      mElementTBody.children().remove();

      // Are we using summaries (e.g., total rows)
      var showSummaries = false;
      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];
        if (c.summary) {
          switch (c.summary.toUpperCase()) {
            case "":
              break;

            case "COUNT":
            case "CUSTOM":
            case "SUM":
            case "$SUM":
              showSummaries = true;
              break;

            default:
              console.warn("widget.UI.Grid: Invalid column summary type '" + c.summary + "'. Supported types are: count, sum, $sum, custom");
          }
        }
      }

      // Add data rows
      if (mVirtualClass) {
        // Add rows to an array so they can be added in bulk for performance reasons
        var tbodyRows = [];
        var groupIndex = 0;
        var groupByColumn = null;

        // Sort Virtual Data?
        if (mOptions.sortByColumn || (mOptions.groupByColumns && mOptions.groupByOrder != "")) {
          if (mOptions.groupByColumns) {
            var g = mOptions.groupByColumns;
            if (mOptions.groupByOrder == "DESC") g = "-" + g;

            var s = mOptions.sortByColumn;
            if (mOptions.sortByDesc) s = "-" + s;
            mVirtualData.sort(GridSorter([g, s]));
          }
          else {
            var s = mOptions.sortByColumn;
            if (mOptions.sortByDesc) s = "-" + s;
            mVirtualData.sort(GridSorter([s]));
          }
          mSorted = true;
        }
        else {
          // Unsort?
          if (mSorted) {
            mSorted = false;
            VirtualDataRefresh(mVirtualClass, true, {}, true);
          }
        }

        var groupStartIndex = 0;
        var groupRow;
        for (var i = 0; i < mVirtualData.length; i++) {
          // Initialise
          var dataRow = mVirtualData[i];

          if (dataRow) {
            // Create Group By Row
            // NOTE: Currently only a single group by is supported
            if (mOptions.groupByColumns) {
              var group = null;
              if (dataRow.cells[mOptions.groupByColumns]) {
                group = dataRow.cells[mOptions.groupByColumns].sortValue || dataRow.cells[mOptions.groupByColumns].value;
              }
              if (group === undefined || group === null) group = "(none)";

              if (LastGroup === null || LastGroup != group) {
                // Group summary footer?
                if (showSummaries && LastGroup != null) {
                  tbodyRows.push(CreateSummaryRow(mVirtualData, groupStartIndex, i - 1, mOptions.groupByColumns));
                  groupStartIndex = i;
                }

                // Create group header table row
                groupIndex += 1;
                groupRow = $("<tr listIndex='-1' class='group-header'></tr>");
                var groupTd = $("<td></td>");
                var colspan = mColumns.length;// countVisible;
                if (mOptions.rowNumbering || mOptions.allowMultiRowSelect || mOptions.showRowSelectors) colspan += 1;
                groupTd.attr("colspan", colspan);
                var divHeader = $("<div class='group-header'></div>");
                groupTd.append(divHeader);

                // TODO: Raise an event to get the group header text
                var groupText = group;

                if (groupByColumn === null) {
                  for (var c = 0; c < mColumns.length; c++) {
                    var col = mColumns[c];
                    if (col && col.key && col.key.toUpperCase() == mOptions.groupByColumns.toUpperCase()) {
                      groupByColumn = col;
                      break;
                    }
                  }
                }
                if (groupText && groupByColumn) {
                  switch (groupByColumn.type) {
                    case "Date":
                      groupText = widget.FormatDateForGrid(groupText);
                      break;

                    case "DateTime":
                      groupText = widget.FormatDateForGrid(groupText, true, groupByColumn.longTime);
                      break;
                  }
                }

                var divCaption = $("<div class='caption'>" + HtmlEncode(groupText) + "</div>");
                divHeader.append(divCaption);

                // Group count
                var count = 0;
                var countVisible = 0;
                  
                for (var j = i; j < mVirtualData.length; j++) {
                  var dataRow2 = mVirtualData[j];
                  var group2 = null;
                  if (dataRow2.cells[mOptions.groupByColumns]) {
                    group2 = dataRow2.cells[mOptions.groupByColumns].sortValue || dataRow2.cells[mOptions.groupByColumns].value;
                  }
                  if (group2 === undefined || group2 === null) group2 = "(none)";

                  if (group == group2) {
                    count += 1;
                    if (!dataRow2.hidden) countVisible += 1;
                  }
                  else {
                    break;
                  }
                }

                if (mOptions.showGroupCounts) {
                  divCaption.append("<div class='count'>" + count + "</div>");
                }

                // Collapse/ expand group button
                if (mOptions.allowGroupingsCollapse) {
                  var ghb = $("<div group-index='" + groupIndex + "' class='collapse-expand'></div>");
                  if (mOptions.groupingsCollapsed) ghb.addClass("collapsed");
                  divHeader.append(ghb);
                  (function (r, e) {
                    r.click(function () {
                      var gi = e.attr("group-index");

                      if (e.hasClass("collapsed")) {
                        e.removeClass("collapsed");
                        $("tr[group-index='" + gi + "']", mElementTBody).removeClass("group-collapsed");
                      }
                      else {
                        e.addClass("collapsed");
                        $("tr[group-index='" + gi + "']", mElementTBody).addClass("group-collapsed");
                      }

                      // Sticky headers may need realigning
                      if (mStickyHeaderElement) ResizeStickyHeader();
                    });
                  })(groupRow, ghb);
                }

                // Hide group header?
                if (afterSort && mHiddenRowsVisible) {
                  // Do not hide
                }
                else {
                  if (countVisible == 0) groupRow.addClass("hidden");
                }

                // Add row
                groupRow.append(groupTd);
                tbodyRows.push(groupRow);

                // Next group
                LastGroup = group;
              }
            }

            // Create table row
            var row = $("<tr listIndex='" + dataRow.listIndex + "' class='datarow'></tr>");
            mDataRowElements.push(row);

            // Grouping
            if (groupIndex != 0) {
              row.attr("group-index", groupIndex);
              if (mOptions.groupingsCollapsed) {
                row.addClass("group-collapsed");
              }
            }

            // Add table cells
            RefreshRow_UpdateData(i, row, false, afterSort);

            // Not showing column headers so apply widths to first row
            if (i == 0 && !mOptions.showColumnHeaders) {
              var tds = $("td,th", row);
              if (tds.length == mColumns.length) {
                for (var j = 0; j < mColumns.length; j++) {
                  var col = mColumns[j];
                  if (col.width) {
                    $(tds[j]).css("width", col.width);
                  }
                }
              }
            }

            // Count Hidden
            if (dataRow.hidden && !afterSort) mCountHidden += 1;

            // Add row
            tbodyRows.push(row);
          }
        }

        // Group summary footer?
        if (showSummaries && LastGroup != null) {
          tbodyRows.push(CreateSummaryRow(mVirtualData, groupStartIndex, mVirtualData.length - 1, mOptions.groupByColumns));
          groupStartIndex = i;
        }

        // Grid summary row
        if (showSummaries) {
          tbodyRows.push(CreateSummaryRow(mVirtualData, 0, mVirtualData.length - 1, ""));
        }

        // Add rows to tbody in bulk for performance
        mElementTBody.append(tbodyRows);

        // Add template row
        if (mOptions.allowAddRows && !mOptions.readOnly) {
          mTemplateRow = $("<tr listIndex='-1' class='templaterow'></tr>");

          RefreshRow_UpdateData(-1, mTemplateRow);

          mElementTBody.append(mTemplateRow);

          mTemplateRow.bind("click", function (e) {
            // Exit edit mode?
            // NOTE: Must do this before changing active row or cell!
            if (mEditing) EditorExitEditMode(false);

            // Add row
            if (AddRow(true)) {
              // Activate cell
              var c = GetColumnByKey($(e.target).attr("key"));
              var ci = -1;
              if (c) {
                ci = GetColumnIndexFromKey(c.key);
              }
              ActiveColumnIndex(ci);
            }
            else {
              // Row not added, e.g., max limit reached
              console.warn("Maximum new grid rows limit reached.");
            }
          });
        }

        // Handle events (accounting for rows added via the AddRow method)
        UpdateElement_HandleEvents();
      }

      // Sticky Header?
      if (mOptions.stickyHeader && mOptions.showColumnHeaders) UpdateElement_StickyHeaders();

      // Context Menu
      // NOTE: #debug can be appended to the URL to prevent this since it makes it hard to debug HTML elements
      if (mOptions.showContextMenu && document.location.hash.toUpperCase() != "#DEBUG") {
        // Only bind to TR elements, otherwise jQuery may have call stack issues on huge grids (J033765)
        //HandleContextMenuEvent($("*", mWrapperElement), function (e) {
        HandleContextMenuEvent($("tr", mWrapperElement), function (e) {
          // Context menu
          var listIndex = $(e.delegateTarget).closest("tr").attr("listIndex");
          if (listIndex !== undefined) ActiveDataRowListIndex(listIndex);

          // Prevent Edge/ IE from showing context menu when formshow link clicked otherwise 2 overlapping menus appear
          // NOTE: This fix is different to the one in finPOWER Connect Cloud Grids
          try {
            var html = $(this).attr("href");
            if (html.toUpperCase().indexOf("APP://FORMSHOW?") > -1) {
              e.preventDefault();
              return false;
            }
          }
          catch (e) {
            // Ignore
          }

          var e2 = { contextMenuEventArgs: e, row: { listIndex: listIndex } };
          if (mOptions.onContextMenuShow) {
            mOptions.onContextMenuShow(e, e2);
          }
          else {
            ShowContextMenu(e, e2);
          }

          e.preventDefault();
          return false;
        });
      }

      // Selected column
      if (mOptions.selectedColumnKey) SelectedColumnKey(mOptions.selectedColumnKey);

      // 'Hidden' rows indicator
      if (mCountHidden != 0 && mOptions.showHiddenRowsPopup) {
        mCaption_Refresh();
      }
      else {
        mCaption = "";
      }

      // Show/ hide caption
      if (mCaption) mCaptionElement.show(); else mCaptionElement.hide();

      // Refresh buttons
      RefreshButtons();

      // Update Editor
      EditorUpdate(false, true);

      // Finalise
      mColumnsDirty = false;
      UpdateAutoHideColumns();
    }

    function UpdateElement_StickyHeaders() {
      if (mSupportsStickyHeaders) {
        // Native browser support
        // NOTE: Applied directly in the widget.css stylesheet
      }
      else {
        // Browser doesn't support this
        // NOTE: Have fully removed support for now
      }
    }

    // -----------------------------------
    // PRIVATE: Show built-in context menu
    // -----------------------------------
    function ShowContextMenu(e, e2) {
      // Create Popup Menu
      if (!mMenuPopup) {
        mMenuPopup = new MenuPopup(mElement, {});
      }
      mMenuPopup.OnAction(ContextMenu_Action);

      // Define Menu Items
      var items = [];

      // Miscellaneous
      if (mOptions.sortByColumn) {
        items.push({ ItemId: "SortClear", Caption: "Clear Sorting", Icon: "Sort_Ascending|Clear" });
      }
      if (mOptions.allowSearchBox) {
        items.push({ ItemId: "SearchBoxToggle", Caption: (mSearchVisible ? "Hide" : "Show") + " Filter Box", Icon: "Filter", Checked: mSearchVisible });
      }
      if (mCountHidden != 0) {
        items.push({ ItemId: "HiddenToggle", Caption: (mHiddenRowsVisible ? "Hide" : "Show") + " Hidden Rows", Icon: "Grid_Row", Checked: mHiddenRowsVisible });
      }
      if (mOptions.groupByColumns && mOptions.allowGroupingsCollapse) {
        if (items.length > 0) items.push({ ItemType: "Separator" });
        items.push({ ItemId: "GroupingsCollapseAll", Caption: "Collapse all Groups", Icon: "Grid_Row|ArrowUp" });
        items.push({ ItemId: "GroupingsExpandAll", Caption: "Expand all Groups", Icon: "Grid_Row|ArrowDown" });
      }

      // Export
      items.push({ ItemType: "SubMenu", Caption: "Export Grid" });
      items.push({ ItemId: "Export_MSEXCELWORKBOOK", Caption: "MS Excel", Icon: "Application_Excel" });
      items.push({ ItemId: "Export_CSV", Caption: "CSV", Icon: "Export_Csv" });
      items.push({ ItemId: "Export_PDF", Caption: "PDF", Icon: "DocumentType_PDF" });
      items.push({ ItemId: "Export_HTML", Caption: "HTML", Icon: "Control_Html" });
      mMenuPopup.Define(items);

      // Show
      if (items.length != 0) mMenuPopup.Show(e.clientX, e.clientY);
    }
    function ContextMenu_Action(actionId) {
      switch (actionId) {
        case "Export_CSV":
          ExportData("CSV");
          break;

        case "Export_HTML":
          ExportData("HtmlTable");
          break;

        case "Export_MSEXCELWORKBOOK":
          ExportData("MSEXCELWORKBOOK");
          break;

        case "Export_PDF":
          ExportData("PDF");
          break;

        case "GroupingsCollapseAll":
          $("tr.group-header div", mElementTBody).addClass("collapsed");
          $("tr:not(.group-header)", mElementTBody).addClass("group-collapsed");
          break;

        case "GroupingsExpandAll":
          $("tr.group-header div", mElementTBody).removeClass("collapsed");
          $("tr:not(.group-header)", mElementTBody).removeClass("group-collapsed");
          break;

        case "HiddenToggle":
          ShowHiddenRows(true);
          break;

        case "SearchBoxToggle":
          if (mElementSearch) {
            mSearchVisible = !mSearchVisible;

            if (mSearchVisible) {
              mElementSearch.removeClass("hidden");
            }
            else {
              mElementSearch.addClass("hidden");

              // Clear when hiding
              mTxtSearch.Text("");
            }
          }
          break;

        case "SortClear":
          Sort("", false);
          break;
      }
    }

    // ----------------------------------------
    // PRIVATE: Handle events for grid elements
    // ----------------------------------------
    function UpdateElement_HandleEvents() {
      // Drilldown buttons
      mElement.off("click", "a.is-drilldown, a.is-drilldown-button");
      mElement.on("click", "a.is-drilldown, a.is-drilldown-button", function (e) {
        // Get row and cell clicked
        var tr = $(e.target).closest("tr.datarow");
        var td = $(e.target).closest("td");
        var listIndex = tr.attr("listIndex");
        var index = td.index();

        // Drilldown button
        if (mOptions.rowNumbering || mOptions.allowMultiRowSelect || mOptions.showRowSelectors) index -= 1; // Account for row selector
        var columnKey = mColumns[index].key;
        if (mVirtualData && listIndex >= 0 && listIndex < mVirtualData.length) {
          PerformRowDrilldown(listIndex, columnKey);
        }
      });

      // Click to activate row/ cell
      mElementTBody.off("click", "tr.datarow");
      mElementTBody.on("click", "tr.datarow", function (e) {
        // Get row and cell clicked
        var tr = $(e.target).closest("tr.datarow");
        var td = $(e.target).closest("td");
        var listIndex = tr.attr("listIndex");

        // Do not change active row if row selector checkbox is clicked
        if (mOptions.showRowSelectors && e && e.target && $(e.target).closest("td").hasClass("rowselector")) return;

        // Exit edit mode?
        // NOTE: Must do this before changing active row or cell!
        if (mEditing) EditorExitEditMode(false);

        // Did we click the currently active cell?
        var clickedActiveCell = td.hasClass("is-sel");

        // Activate row by index, NOT listIndex!
        for (var i = 0; i < mDataRowElements.length; i++) {
          if (mDataRowElements[i][0] == tr[0]) {
            ActiveDataRowIndex(i, false, true, td.attr("key"));
            break;
          }
        }

        // Activate cell
        var c = GetColumnByKey(td.attr("key"));
        var ci = -1;
        if (c) {
          ci = GetColumnIndexFromKey(c.key);
        }
        ActiveColumnIndex(ci);

        // Clicking active cell to go into edit mode?
        if (mEditable && c && clickedActiveCell) {
          if (c.allowEdit && c.type.toUpperCase() != "BOOLEAN") {
            if (EditorExitEditMode(false)) {
              EditorEnterEditMode();
            }
            else {
              // NOTE: No concept of failing to commit
            }
          }
          else {
            EditorExitEditMode(false);
          }
        }
      });

      // Double-click to drilldown (but not if editable)
      if (!mEditable) {
        mElementTBody.off("dblclick", "tr.datarow");
        mElementTBody.on("dblclick", "tr.datarow", function (e) {
          // Get row and cell clicked
          var tr = $(e.target).closest("tr.datarow");
          var listIndex = tr.attr("listIndex");

          if (mVirtualData && listIndex >= 0 && listIndex < mVirtualData.length) PerformRowDrilldown(listIndex, "");

          // Double-clicking may have selected text so de-select providing we are handling the RowDrilldown event
          if (mOptions.onRowDrilldown && window.getSelection) {
            window.getSelection().removeAllRanges();
          }
        });
      }
    }

    // ------------------------
    // PRIVATE: Enter edit mode
    // ------------------------
    function EditorEnterEditMode() {
      // Read-Only?
      if (mOptions.readOnly) return;

      // Commit current changes?
      if (mEditing) EditorExitEditMode();

      // Initialise
      var c = GetColumnByIndex(mActiveColumnIndex);
      if (!c || !c.allowEdit) return false;
      var dataRow = mVirtualData[mActiveDataRowIndex];
      var cellData = dataRow.cells[mActiveColumnKey];

      // Read-Only?
      if (dataRow.readOnly || cellData.readOnly || cellData.notApplicable) return;

      // Flag new rows as no longer being new
      if (dataRow.newRow) dataRow.newRow = false;

      // Create default Editor information
      var editorInfo = {};
      switch (c.type.toUpperCase()) {
        case "BOOLEAN":
          // Edited via inline checkbox
          return;

        case "CURRENCY":
          editorInfo.type = "numberbox";
          editorInfo.decimals = -1;
          break;

        case "DATE":
          editorInfo.type = "datebox";
          editorInfo.historic = false;
          break;

        case "DOUBLE":
          editorInfo.type = "numberbox";
          editorInfo.decimals = c.decimals;
          break;

        case "INTEGER":
          editorInfo.type = "numberbox";
          editorInfo.decimals = 0;
          break;

        case "STRING":
        case "CODE":
          if (c.listCsv) {
            // CSV List
            if (c.listMulti) {
              // CheckList
              editorInfo.type = "checklist";
              editorInfo.listCsv = c.listCsv;
            }
            else {
              // ComboBox
              editorInfo.type = "listbox";
              editorInfo.canLimitToList = true;
              editorInfo.limitToList = c.limitToList ? true : false;
              editorInfo.listCsv = c.listCsv;
              editorInfo.collection = null;
              editorInfo.standardRange = null;
              editorInfo.wrap = c.wrap;
            }
          }
          else if (c.collection) {
            // Collection
            editorInfo.type = "dbcombo";
            editorInfo.canLimitToList = true;
            editorInfo.limitToList = c.limitToList ? true : false;
            editorInfo.collection = c._collection;
            editorInfo.standardRange = null;
          }
          else if (c.list) {
            // Resolvable List
            editorInfo.type = "dbcombo";
            editorInfo.canLimitToList = c._collection.loaded; // Cannot limit to list unless loaded
            editorInfo.limitToList = c.limitToList ? true : false;
            editorInfo.collection = c._collection;
          }
          else if (c.standardRange) {
            // Standard Range
            editorInfo.type = "dbcombo";
            editorInfo.includeInactive = c.includeInactive ? true : false;
            editorInfo.limitToList = c.limitToList ? true : false;
            editorInfo.standardRange = c.standardRange;
            editorInfo.sqlWhere = c.sqlWhere;
            editorInfo.displayColumns = c.displayColumns;
          }
          else {
            editorInfo.type = "textbox";
          }
          editorInfo.maxLength = c.maxLength ? c.maxLength : 0;
          editorInfo.wrap = c.wrap;
          break;

        default:
          console.warn("No default editor defined for column type '" + c.type + "'.");
      };

      // Notify
      if (mOptions.onBeforeCellEdit) {
        // Create event object
        var e = { row: { listIndex: mActiveDataRowIndex }, columnKey: mActiveColumnKey, cancel: false, editorInfo: editorInfo };

        // Call
        mOptions.onBeforeCellEdit(e);

        // Cancelled?
        if (e.cancel) return false;
      }

      // Editing
      mEditing = true;
      mEditorInfo = editorInfo;

      // Update editor info
      editorInfo.valueOriginal = cellData.value;

      // Update Editor
      EditorUpdate(true);

      return true;
    }

    // -----------------------
    // PRIVATE: Exit edit mode
    // -----------------------
    function EditorExitEditMode(cancel) {
      // Editing?
      if (!mEditing) return true;

      //console.log("grid editor exit edit mode: cancel="+cancel);
      // Cancelling?
      if (cancel) {
        mEditing = false;
        mEditingDbComboSpecial = false;

        // Update Editor
        EditorUpdate();

        return true;
      }
      else {
        // No longer editing
        mEditing = false;
        mEditingDbComboSpecial = false;

        // Get new value
        var newValue;
        switch (mEditorInfo.type.toUpperCase()) {
          case "CHECKLIST":
            newValue = mEditElementControls.checklist.Text();
            break;

          case "DATEBOX":
            newValue = Runtime_ParseDate(mEditElementControls.textbox.Text(), mEditorInfo.historic, true);
            break;

          case "DBCOMBO":
            newValue = mEditElementControls.dbcombo.Text();

            // Limit to list?
            if (mEditorInfo.canLimitToList && mEditorInfo.limitToList) {
              if (!mEditElementControls.dbcombo.ListExists(newValue)) {
                newValue = "";
              }
            }
            else {
              // Cannot really limit to list in case they are still fetching
            }
            break;

          case "LISTBOX":
            newValue = mEditElementControls.listbox.Text();
            break;

          case "NUMBERBOX":
            // Massive number that is formatted in a way that will mess up serialisation?
            var jsNumber = "" + mEditElementControls.numberbox.Value();
            if (jsNumber && (jsNumber.indexOf("e") != -1 || jsNumber.length >= 16)) {
              newValue = 0;
              console.warn("Attempted to set Grid NumberBox value to '" + jsNumber + "' which is likely to cause serialisation or parsing issues.");
            }
            else {
              newValue = mEditElementControls.numberbox.Value();
            }
            break;

          case "TEXTBOX":
            newValue = mEditElementControls.textbox.Text();
            break;

          default:
            console.warn("No editor handled for exiting edit mode for editorInfo type '" + mEditorInfo.type + "'.");
            newValue = undefined;
        }

        // Commit changes
        if (newValue === undefined) {
          // Cannot update
          console.warn("cannot update!");
        }
        else {
          PerformBeforeCellUpdate(mActiveDataRowIndex, mActiveColumnKey, newValue, true);
        }

        // Update Editor
        EditorUpdate(false);

        return true;
      }
    }

    // ----------------------
    // PRIVATE: Update editor
    // ----------------------
    function EditorUpdate(enteringEditMode, updatingElement) {
      // Validate
      if (mActiveDataRowIndex < 0 || mActiveDataRowIndex > mDataRowElements.length - 1) {
        mEditing = false;
        mEditingDbComboSpecial = false;
      }
      else if (!mEditable || mActiveColumnIndex == -1 || mActiveDataRowIndex == -1) {
        mEditing = false;
        mEditingDbComboSpecial = false;
      }
      if (!mEditing) {
        mEditCell = null;
        mEditElement.hide();
      }
      if (!mEditing) {
        if (updatingElement) {
          // Prevent focus being called since this takes input focus from other controls!
        }
        else {
          // Save Scroll Top (for IE11 issues)
          var st = mTableWrapper.scrollTop();

          mElement.focus();

          // Restore Scroll Top (for IE11 issues)
          mTableWrapper.scrollTop(st);
        }

        return;
      }

      // Locate cell
      var tr = mDataRowElements[mActiveDataRowIndex];
      var td = $("td[key='" + mActiveColumnKey + "']", tr);
      if (td.length == 1) {
        mEditCell = td;
      }
      else {
        mEditCell = null;
      }

      // Initialise editor control
      if (mEditCell) {
        // Position
        var pos = mEditCell.position();
        mEditElement.css({ left: pos.left + "px", top: pos.top + "px", height: mEditCell.outerHeight() + "px", width: mEditCell.outerWidth() + "px" });
        mEditElement.show();

        if (enteringEditMode) {
          // Initialise control
          mEditElementControls.checklist.Visible(false);
          mEditElementControls.dbcombo.Visible(false);
          mEditElementControls.listbox.Visible(false);
          mEditElementControls.numberbox.Visible(false);
          mEditElementControls.textbox.Visible(false);

          switch (mEditorInfo.type.toUpperCase()) {
            case "CHECKLIST":
              mEditElementControls.checklist.Visible(true);
              if (!mEditorInfo.valueOriginal) mEditorInfo.valueOriginal = ""; // Undefined, null etc
              mEditElementControls.checklist.Text(mEditorInfo.valueOriginal);
              mEditElementControls.checklist.ListFromCsvString(mEditorInfo.listCsv);
              mEditElementControls.checklist.Focus();
              break;

            case "DATEBOX":
              mEditElementControls.textbox.Visible(true);
              if (typeof mEditorInfo.valueOriginal == "string") {
                // Most likely an ISO 8601 string
                mEditorInfo.valueOriginal = Runtime_ParseJsonDate(mEditorInfo.valueOriginal);
              }
              if (!mEditorInfo.valueOriginal) mEditorInfo.valueOriginal = null; // Undefined, null etc
              mEditElementControls.textbox.Text(Runtime_FormatDate(mEditorInfo.valueOriginal, false, true));
              mEditElementControls.textbox.Element().css("text-align", "right");
              mEditElementControls.textbox.Focus();
              break;

            case "DBCOMBO":
              mEditElementControls.dbcombo.Visible(true);
              mEditElementControls.dbcombo.Element().css({ "word-wrap": "break-word", "word-break": "break-all" });

              var el0 = mEditElementControls.dbcombo.Element()[0];
              el0.style.setProperty("background-color", "white", "important");
              el0.style.setProperty("border", "none", "important");
              el0.style.setProperty("border-radius", "0", "important");
              el0.style.setProperty("height", mEditElement.innerHeight() + "px", "important");
              el0.style.setProperty("padding", "2px", "important");
              el0.style.setProperty("line-height", "24px", "important");

              if (!mEditorInfo.valueOriginal) mEditorInfo.valueOriginal = ""; // Undefined, null etc
              mEditElementControls.dbcombo.Text(mEditorInfo.valueOriginal);
              mEditElementControls.dbcombo.LimitToList(mEditorInfo.limitToList);
              if (!mEditorInfo.limitToList) {
                if (mEditorInfo.maxLength) {
                  mEditElementControls.dbcombo.MaxLength(mEditorInfo.maxLength);
                }
                else {
                  mEditElementControls.dbcombo.MaxLength(255);
                }
              }

              if (mEditorInfo.standardRange) {
                // Standard Range
                mEditElementControls.dbcombo.RefreshFromStandardRange(mEditorInfo.standardRange, mEditorInfo.sqlWhere, mEditorInfo.includeInactive, "", mEditorInfo.displayColumns);
              }
              else {
                // JavaScript Collection
                mEditElementControls.dbcombo.RefreshFromCollection(mEditorInfo.collection.data, mEditorInfo.collection.idColumn, mEditorInfo.collection.displayColumns);
              }
              mEditElementControls.dbcombo.UpdateElement();
              mEditElementControls.dbcombo.Focus();

              if (mEditElementControls.dbcombo.IsSpecialStandardRange()) {
                // Do not drop down special standard ranges such as Accounts otherwise it becomes impossible to clear the value
                mEditingDbComboSpecial = true;
              }
              else {
                var ti = window.setTimeout(function () {
                  window.clearTimeout(ti);
                  ti = null;

                  // Slight delay to let things catch up
                  mEditElementControls.dbcombo.DropdownShow();
                }, 10);
              }
              break;

            case "LISTBOX":
              mEditElementControls.listbox.Visible(true);
              mEditElementControls.listbox.Element().css({ border: "none", borderRadius: 0, "word-wrap": "break-word", "word-break": "break-all" });
              var el0 = mEditElementControls.listbox.Element()[0];
              el0.style.setProperty("background-color", "white", "important");
              el0.style.setProperty("border", "none", "important");
              el0.style.setProperty("border-radius", "0", "important");
              el0.style.setProperty("height", mEditElement.innerHeight() + "px", "important");
              el0.style.setProperty("padding", "2px", "important");
              el0.style.setProperty("line-height", "24px", "important");

              if (!mEditorInfo.valueOriginal) mEditorInfo.valueOriginal = ""; // Undefined, null etc
              mEditElementControls.listbox.Text(mEditorInfo.valueOriginal);
              mEditElementControls.listbox.LimitToList(mEditorInfo.limitToList);
              mEditElementControls.listbox.ListFromCsvString(mEditorInfo.listCsv);
              mEditElementControls.listbox.UpdateElement();
              mEditElementControls.listbox.Focus();
              var ti = window.setTimeout(function () {
                window.clearTimeout(ti);
                ti = null;

                // Slight delay to let things catch up
                mEditElementControls.listbox.DropdownShow();
              }, 10);
              break;

            case "NUMBERBOX":
              mEditElementControls.numberbox.Visible(true);
              mEditElementControls.numberbox.Decimals(mEditorInfo.decimals); 
              if (!mEditorInfo.valueOriginal) mEditorInfo.valueOriginal = 0; // Undefined, null etc
              mEditElementControls.numberbox.Value(mEditorInfo.valueOriginal);
              mEditElementControls.numberbox.Focus();
              break;

            case "TEXTBOX":
              mEditElementControls.textbox.Visible(true);
              mEditElementControls.textbox.MaxLength(mEditorInfo.maxLength);
              if (!mEditorInfo.valueOriginal) mEditorInfo.valueOriginal = ""; // Undefined, null etc
              mEditElementControls.textbox.Text(mEditorInfo.valueOriginal);
              var c = GetColumnByKey(mActiveColumnKey);
              if (c && c.align) {
                mEditElementControls.textbox.Element().css("text-align", c.align);
              }
              else {
                mEditElementControls.textbox.Element().css("text-align", "left");
              }
              mEditElementControls.textbox.Focus();
              break;

            default:
              console.warn("No editor defined for editorInfo type '" + mEditorInfo.type + "'.");
          }
        }
      }
      else {
        // Just in case!
        mElement.focus();
        mEditElement.hide();
      }
    }

    // --------------------------------
    // PUBLIC: Refresh the grid buttons
    // --------------------------------
    function RefreshButtons() {
      var bl, button, e;
      var hasActionsList = false;
      var hasButtons = false;
      var hasRowActions = false;

      // Just in case!
      if (!mButtonsElement) return;

      // Clear existing
      mButtonsElement.children().remove();

      // Add buttons list
      bl = $("<ul></ul>");
      mButtonsElement.append(bl);
      bl.addClass("group"); // Always appear grouped (this just looks better with round buttons)

      // Create a button for each Action
      var firstActionInGroup = null, hasGroups = false;
      for (var i = 0; i < mActions.Actions().length; i++) {
        // Initialise
        var action = mActions.Actions()[i];

        if (!action.actionId) {
          // Separator
          if (firstActionInGroup) {
            hasGroups = true;
            firstActionInGroup = null;

            // Flag last lot of buttons as being grouped
            bl.addClass("group");

            // New group
            bl = $("<ul></ul>");
            bl.addClass("group");
            mButtonsElement.append(bl);
          }
        }
        else if (action.visible) {
          // Track
          hasButtons = true;

          // Add button
          e = $("<li><button class='is-button'></button></li>");
          bl.append(e);
          button = $("button", e);

          // Track
          if (!firstActionInGroup) firstActionInGroup = e;
          hasButtons = true;

          // Update
          if (action.caption) button.text(action.caption);
          if (action.tooltipText) button.attr("title", action.tooltipText);
          if (!action.enabled) button.attr("disabled", "disabled");
          if (action.icon) {
            var iconUrl = widget.GetIconUrl(action.icon, 16);
            if (iconUrl) {
              iconUrl = iconUrl.replace(/\\/g, "/");  // Backslash to forward slash when running from local file system
              button.css({ backgroundImage: "url(" + iconUrl + ")" });
            }
            button.addClass("icon");
          }
          if (action.checked) button.addClass("checked");

          if (action.buttonStyle) {
            button.addClass(action.buttonStyle);
          }
          else {
            // Automatic styles
            // NOTE: Not applicable to HTML Widgets
            switch (action.actionId.toUpperCase()) {
              //case "ADD":
              //  button.addClass("positive");
              //  break;

              //case "REFRESH":
              //  button.addClass("refresh");
              //  e.addClass("system"); // Float to the left
              //  button.attr("title", "Refresh");
              //  break;

              default:
                button.addClass("normal");
                break;
            }
          }

          // Handler
          if (action.handler) {
            // Custom handler
            (function (action) { button.click(function () { action.handler(); }); })(action);
          }
          else {
            // Default handler
            (function (action) { button.click(function () { ExecuteAction(action.actionId); }); })(action);
          }
        }
        else {
          // Separator
          if (firstActionInGroup) {
            hasGroups = true;
            firstActionInGroup = null;

            // Flag last lot of buttons as being grouped
            bl.addClass("group");

            // New group
            bl = $("<ul></ul>");
            bl.addClass("group");
            mButtonsElement.append(bl);
          }
        }
      }

      // Show/ hide Button Strip
      if (hasButtons) {
        mButtonsElement.show();
      }
      else {
        mButtonsElement.hide();
      }
    }

    // --------------------------
    // PUBLIC: Actions collection
    // --------------------------
    function Actions() {
      return mActions;
    }

    // -------------------------
    // PUBLIC: Execute an Action
    // -------------------------
    function ExecuteAction(actionId) {
      if (mOptions.onAction) {
        mOptions.onAction(actionId);
      }
      else {
        window.alert("widget.UI.Grid.ExecuteAction: No OnAction defined for this Grid object.");
      }
    }

    // --------------------
    // Resize Sticky Header
    // --------------------
    function ResizeStickyHeader() {
      // Wrapper dimensions
      var wpos = mWrapperElement.offset();
      var ww = mWrapperElement.outerWidth();
      var wiw = mWrapperElement.innerWidth();
      var wh = mWrapperElement.outerHeight();
      //var sl = mWrapperElement.scrollLeft();
      var sl = mTableWrapper.scrollLeft();
      var st = mWrapperElement.scrollTop();
      var w = mElement.outerWidth();

      // Sticky Header
      if (mStickyHeaderElement) {
        mStickyHeaderElement.css({ width: w + "px" });
        mStickyHeaderElement.css({ "margin-left": -sl + "px" });
        //console.warn("scroll top: " + st);
        mStickyHeaderWrapperElement.css("top", st + "px");

        // Synchronise column widths (ensure colspans work)
        var ths = $("thead > tr > th", mElement);
        var thsSticky = $("thead > tr > th", mStickyHeaderElement);
        for (var i = 0; i < ths.length; i++) {
          var th = $(ths[i]);
          var thSticky = $(thsSticky[i]);
          thSticky.css("width", th.outerWidth() + "px");
        }

        // Clip header width
        //mStickyHeaderWrapperElement.css({ "max-width": ww + "px", overflow: "hidden" });
      }

      // Footer
      if (mStickyFooterElement) {
        mStickyFooterElement.css({ width: ww + "px", top: (wh + wpos.top) + "px" });
        mWrapperElement.css({ "margin-bottom": "36px" }); // Ensure grid rows can scroll into view and are not hidden behind footer
      }
    }

    // --------------------
    // Create a Summary Row
    // --------------------
    function CreateSummaryRow(data, startIndex, endIndex, groupName) {
      var tr = $("<tr class='footer'></tr>");

      // Account for Row Selectors
      if (mOptions.rowNumbering || mOptions.allowMultiRowSelect || mOptions.showRowSelectors) {
        tr.append("<td></td>");
      }

      if (groupName) {
        // Group summary
        tr.addClass("is-row-footer");
      }
      else {
        // Table summary
        tr.addClass("is-row-footer-bold");
      }

      // Get an array of list indexes (since the grid may be sorted)
      if (mOptions.onFooterCellFormat) {
        var listIndexes = [];

        for (var i = startIndex; i <= endIndex; i++) {
          listIndexes.push(data[i].listIndex);
        }
      }

      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];

        if (c.visible) {
          var td = $("<td></td>");
          td.attr("key", c.key);

          // Format Cell from Column
          FormatColumnCell(c, td, "");

          if (c.summary) {
            switch (c.summary.toUpperCase()) {
              case "COUNT":
                // Count
                td.text(widget.FormatNumber((endIndex - startIndex + 1), 0, true));
                break;

              case "SUM":
              case "$SUM":
                // Sum
                var total = 0;
                for (var j = startIndex; j <= endIndex; j++) {
                  var item = data[j].cells[c.key];
                  if (item && item.value) {
                    total += parseFloat(item.value);
                  }
                }

                var s = "" + total;

                switch (c.type.toUpperCase()) {
                  case "CURRENCY":
                    s = widget.FormatCurrency(total, c.summary.substr(0, 1) == "$");
                    break;

                  case "DOUBLE":
                    s = widget.FormatNumber(total, c.decimals, true);
                    break;

                  case "INTEGER":
                    s = widget.FormatNumber(total, 0, true);
                    break;

                  default:
                    break;
                }

                td.text(s);
                break;

              default:
                td.html("&nbsp;");
            }

            // Allow event to update
            if (mOptions.onFooterCellFormat) {
              var originalCellText = td.text();
              var e = {
                key: c.key,
                listIndexes: listIndexes,
                cell: td,
                cellText: originalCellText,
                row: tr,
              };

              try {
                mOptions.onFooterCellFormat(e);
              }
              catch (ex) {
                console.warn("widget.UI.Grid: Error calling onFooterCellFormat: " + ex);
              }

              // Update cell?
              if (e.cellText != originalCellText) {
                td.text(e.cellText);
              }
            }
          }

          tr.append(td);
        }
      }

      return tr;
    }

    // -----------------------
    // Multi-field Grid Sorter
    // -----------------------
    function GridSorter(fields) {
      return function (a, b) {
        return fields
          .map(function (o) {
            var dir = 1;
            if (o[0] == "-") {
              dir = -1;
              o = o.substring(1);
            }

            var av, bv;
            if (a && a.cells[o]) av = a.cells[o].sortValue || a.cells[o].value;
            if (b && b.cells[o]) bv = b.cells[o].sortValue || b.cells[o].value;

            // Case-insensitive
            if (av === undefined || av === null) av = "";
            if (bv === undefined || bv === null) bv = "";
            if (typeof av == "string") av = av.toUpperCase();
            if (typeof bv == "string") bv = bv.toUpperCase();

            if (av > bv) return dir;
            if (av < bv) return -(dir);
            return 0;
          })
          .reduce(function firstNonZeroValue(p, n) {
            return p ? p : n;
          }, 0);
      };
    }

    // ---------------
    // Update Row Data
    // ---------------
    function RefreshRow_UpdateData(i, row, refresh, afterSort) {
      afterSort = afterSort || false;

      // If refreshing row, remove cells, classes etc
      if (refresh) {
        row.children().remove();
        row.removeClass("hidden inactive strike special1 expired selected row-selected invalid readonly new");
        row.attr("style", "");
      }

      // Initialise
      var cells = [];
      var dataRow = (i == -1 ? {} : mVirtualData[i]);

      // Add row selector/ number cell
      if (mOptions.rowNumbering || mOptions.allowMultiRowSelect || mOptions.showRowSelectors) {
        // Selector cell
        var rs = $("<td class='rowselector is-no-select'></td>");

        // Debug
        //rs.attr("title", "List index: " + row.attr("listIndex"));

        // Selector checkbox
        if (mOptions.allowMultiRowSelect && i != -1) {
          var checked = dataRow.rowSelectorCheckBox && dataRow.rowSelectorCheckBox.Value();
          var chk = $("<input type='checkbox'/>");
          rs.append(chk);
          dataRow.rowSelectorCheckBox = new widget.UI.CheckBox(chk, {
            onChange: function () {
              if (dataRow.rowSelectorCheckBox.Value()) {
                row.addClass("row-selected");
              }
              else {
                row.removeClass("row-selected");
              }

              // Update caption
              mSelectedRowCountElement_Refresh();

              // Notify
              if (mOptions.onSelectedRowsChanged) {
                mOptions.onSelectedRowsChanged({});
              }
            }
          });
          dataRow.rowSelectorCheckBox.Value(checked);

          // Row Selected
          if (checked) row.addClass("row-selected");
        }

        // Row numbering
        if (mOptions.rowNumbering && i != -1) {
          rs.append("<span class='rownumber'>" + (i + 1) + "</span>");
        }

        // Icon
        if (dataRow.rowSelectorIcon) {
          var iconUrl = widget.GetIconUrl(dataRow.rowSelectorIcon, 16);
          if (iconUrl) {
            rs.css({ backgroundImage: "url(" + iconUrl + ")" });
            rs.addClass("icon");
          }
        }
        if (dataRow.details) {
          rs.attr("title", dataRow.details);
        }

        // Template row?
        if (i == -1) {
          rs.append("<span class='templaterow'></span>");
        }

        // Insert
        cells.push(rs);
      }

      // Invalid state
      if (dataRow && dataRow.invalid) {
        //if (dataRow.newRow) {
        //  // Ignore for new, unedited rows since it is up to user code to clean up unedited items
        //}
        //else {
        row.addClass("invalid");
        //}
      }
      if (dataRow && (dataRow.newRow == true || dataRow.newRow == false)) {
        row.addClass("new");
      }

      // Cells
      for (var j = 0; j < mColumns.length; j++) {
        // Initialise
        var c = mColumns[j];

        if (true) {//c.elementCreatedIndex != -1) {
          // Create
          var td = $("<td></td>");
          td.attr("key", c.key);

          // Format Cell from Column
          FormatColumnCell(c, td, "");

          // Other formatting
          if (c.align) td.css("text-align", c.align);
          if (c.colour) td.css("color", c.colour);
          if (c.noLineBreak) td.addClass("nobreak");

          // Formatting for when column headers not showing
          if (!mOptions.showColumnHeaders) {
            switch (c.type) {
              case "Drilldown":
                if (c.width) td.css("width", c.width);
                break;
            }
          }

          // Tweak cell data
          var cellData = (i == -1 ? { value: null } : dataRow.cells[c.key]);
          if (cellData.notApplicable) {
            cellData.value = null;
          }

          // Null cell?
          var nullCell = false;
          if (cellData.value === null || cellData.value === undefined) {
            nullCell = true;

            switch (c.type.toUpperCase()) {
              case "BOOLEAN":
                // Booleans should always show if editing is allowed
                if (i == -1) {
                  // Template row
                  nullCell = true;
                }
                else {
                  nullCell = !c.allowEdit;
                }
                break;

              case "DRILLDOWN":
                // Drilldowns should always show regardless of whether value is null
                if (i == -1) {
                  // Template row
                  nullCell = true;
                }
                else {
                  nullCell = false;
                }
                break;

              default:
                // Other controls should always show blank, regardless of whether they are editable or not
                break;
            }
          }

          // Update
          if (!cellData) {
            window.alert("Invalid column key '" + c.key + "'");
            break;
          }
          else if (nullCell) {
            // No value and cell is not an editable boolean or drilldown
            if (i == -1) {
              // Template row
              td.html("&nbsp;");
            }
          }
          else {
            // Format value based on data type
            td.addClass("is-grid-col-" + c.type.toLowerCase());

            switch (c.type.toUpperCase()) {
              case "BOOLEAN":
                // Boolean
                if (c.allowEdit && !mOptions.readOnly && !cellData.readOnly && !cellData.notApplicable) {
                  // Editable (booleans are a special type of editor since they always exist rather than just when the grid goes into edit mode)
                  var checkbox = $("<input type='checkbox' class='is-grid-checkbox'/>");
                  checkbox.prop("checked", cellData.value);

                  (function (key, cb, colIndex) {
                    cb.click(function () {
                      var index = checkbox.closest("tr").attr("listIndex");
                      ActiveDataRowListIndex(index);
                      ActiveColumnIndex(colIndex);
                      PerformBeforeCellUpdate(mActiveDataRowIndex, key, cb.prop("checked"));
                      mElement.focus();
                    });
                  })(c.key, checkbox, j);
                  td.append(checkbox);
                }
                else {
                  // Read-Only
                  if (cellData.value) {
                    td.addClass("is-grid-col-boolean-true is-symbol-tick");
                  }
                  else {
                    td.addClass("is-grid-col-boolean-false");
                    if (c.showCross) td.addClass("is-symbol-cross");
                  }
                }
                break;

              case "COLOURBLOCK":
                // Colour Block
                if (cellData.value) {
                  td.html("<div class='is-colour-block' style='background-color:" + cellData.value + "'></div>");
                }
                break;

              case "COLOURFLAG":
                // Colour Flag
                if (cellData.value) {
                  var icon = "Flag[" + cellData.value + "]";
                  icon = widget.GetIconUrl(icon, 16);
                  td.html("<img src='" + icon + "' style='width:16px' title='" + HtmlEncode(cellData.value) + "'/>");
                }
                break;

              case "CURRENCY":
                // Currency
                if (cellData.value == null || (cellData.value == 0 && c.blankIfZero)) {
                  td.text("");
                }
                else if (typeof cellData.value == "string") {
                  // E.g., Standard Transactions grid
                  td.text(cellData.value);
                }
                else {
                  td.text(widget.FormatCurrency(cellData.value));
                }
                break;

              case "DATE":
                // Date
                if (cellData.value) {
                  td.text(widget.FormatDateForGrid(cellData.value));
                }
                break;

              case "DATETIME":
                // Date/Time
                if (cellData.value) {
                  td.text(widget.FormatDateForGrid(cellData.value, true, c.longTime));
                }
                break;

              case "DOUBLE":
                // Double
                if (cellData.value == null || (cellData.value == 0 && c.blankIfZero)) {
                  td.text("");
                }
                else if (typeof cellData.value == "string") {
                  // E.g., Standard Transactions grid
                  td.text(cellData.value);
                }
                else {
                  td.text(widget.FormatNumber(cellData.value, c.decimals, c.showSeparators));
                }
                break;

              case "DRILLDOWN":
                // Drilldown
                if (!cellData.value && c.drilldownHideIfBlank) {
                  // No value so hide button
                }
                else {
                  td.html("<a class='is-drilldown-button'></a>");
                  if (c.drilldownGlyph) {
                    $("a", td).addClass(c.drilldownGlyph);
                  }
                  else if (c.icon) {
                    var db = $("a", td);
                    var icon = widget.GetIconUrl(c.icon, 16);
                    db.addClass("icon");
                    db.append("<img src='" + icon + "' style='width:16px'/>");
                  }
                }
                break;

              case "HTML":
                // HTML
                if (cellData.value === null || cellData.value === undefined) {
                  td.text("");
                }
                else {
                  td.html(cellData.value);
                }
                break;

              case "ICON":
                // Icon
                if (cellData.value) {
                  var icon = cellData.value;
                  if (icon.indexOf("/") == -1) {
                    // Not a file name so assume a Web Services Icon Resource Id (optionally "resourceId|overlay")
                    var overlay = "";
                    var oi = icon.indexOf("|");
                    if (oi != -1) {
                      overlay = icon.substr(oi + 1);
                      icon = icon.substr(0, oi);
                    }
                    icon = widget.GetIconUrl(icon, 16, overlay);
                  }
                  td.html("<img src='" + icon + "' style='width:16px'/>");
                }
                break;

              case "INTEGER":
                // Integer
                if (cellData.value == null || (cellData.value == 0 && c.blankIfZero)) {
                  td.text("");
                }
                else {
                  td.text(widget.FormatNumber(cellData.value, 0, true));
                }
                break;

              default:
                // Other
                // NOTE: Set html rather than text so that line breaks are respected
                if (c.truncate) {
                  td.html("<div style='display:table;table-layout:fixed;width:100%'><div style='overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap'>" + widget.UI.HtmlEncode(cellData.value) + "</div></div>");
                  td.attr("title", cellData.value);
                }
                else if (c.wrap) {
                  td.html("<div style='width:100%'>" + widget.UI.HtmlEncode(cellData.value) + "</div>");
                }
                else {
                  td.html(widget.UI.HtmlEncode(cellData.value));
                }
                break;
            }

            // Hyperlink?
            if (cellData.hyperlink) {
              td.wrapInner("<a href=\"" + cellData.hyperlink + "\"></a>");
            }

            // Other cell styles
            if (cellData.backgroundColour) td.css("background-color", cellData.backgroundColour);
            if (cellData.bold) td.css({ "font-weight": "bold" });
            if (cellData.colour) td.css("color", cellData.colour);
            if (cellData.small) td.addClass("small");
            if (cellData.strike) td.addClass("strike");

            // Blank tip
            if (cellData.blankTip && (cellData.value === null || cellData.value === undefined || cellData.value === "")) td.append("<span class='blanktip'>" + HtmlEncode(cellData.blankTip) + "</span>");

            // Callback to get cell value?
            if (cellData.value && cellData.value.eventId) {
              // Clear
              td.text("");

              // Callback
              (function (td, eventId, params) {
                if (cellData.value.systemEvent) {
                  // System event
                  widget._SystemGetString(cellData.value.eventId, params,
                    function (data) {
                      td.text(data);
                    },

                    function (data) {
                      // Error
                      td.text("#ERR");
                      console.warn("Error from grid callback: " + data);
                    }
                  );
                }
                else {
                  // Script event
                  widget.GetString(cellData.value.eventId, params,
                    function (data) {
                      td.text(data);
                    },

                    function (data) {
                      // Error
                      td.text("#ERR");
                      console.warn("Error from grid callback: " + data);
                    }
                  );
                }
              })(td, cellData.value.eventId, cellData.value.params || {});
            }
          }

          // Other cell styles
          if (cellData.notApplicable) td.addClass("notapplicable");
          if (dataRow.readOnly || (cellData && (cellData.readOnly || cellData.notApplicable))) {
            td.addClass("readonly");
            td.removeClass("editable");
          }
          if (c.allowDrilldown && c.type != "Drilldown") {
            td.wrapInner("<a class='is-drilldown'></a>");
          }

          // Tooltip
          if (cellData.tooltipText) {
            td.attr("title", cellData.tooltipText);
          }

          // Add
          cells.push(td);
        }
      }

      // Add all cells in one hit for performance (J033124)
      row.append(cells);

      // Row Style
      if (dataRow.cssClass) row.addClass(dataRow.cssClass);
      if (dataRow.backgroundColour) row.css({ "background-color": dataRow.backgroundColour });
      if (dataRow.bold) row.css({ "font-weight": "bold" });
      if (dataRow.colour) row.css({ "color": dataRow.colour });
      if (dataRow.hidden) {
        if (afterSort && mHiddenRowsVisible) {
          row.addClass("hideable");
        }
        else {
          row.addClass("hidden hideable");
        }
      }
      if (dataRow.inactive) row.addClass("inactive");
      if (dataRow.readOnly) row.addClass("readonly");
      if (dataRow.small) row.addClass("small");
      if (dataRow.strike) row.addClass("strike");
    }

    // -------------------------
    // Format a TH or TD element
    // -------------------------
    function FormatColumnCell(col, cell, type) {
      // Wrap?
      if (col.wrap === true) cell.css("word-break", "break-all");

      // Editable
      if (col.allowEdit) {
        cell.addClass("editable");
      }
      else {
        cell.removeClass("editable");
      }

      // Alignment
      if (!col.align) {
        switch (col.type.toUpperCase()) {
          case "BOOLEAN":
          case "ICON":
            cell.css("text-align", "center");
            break;

          case "CURRENCY":
          case "DATE":
          case "DOUBLE":
          case "INTEGER":
            cell.css("text-align", "right");
            break;

          case "DATETIME":
            cell.css({ "text-align": "right", "white-space": "nowrap" });
            break;
        }
      }

      // No Wrap
      if (col.noWrap) {
        cell.css({ "white-space": "nowrap" });
      }

      // Width
      if (!col.width) {
        switch (col.type.toUpperCase()) {
          case "BOOLEAN":
            cell.css("width", "16px");
            break;

          case "CODE":
            cell.css("width", "8em");
            break;

          case "CURRENCY":
            cell.css("width", "8em");
            break;

          case "DATE":
            cell.css("width", "6em");
            break;

          case "DOUBLE":
            cell.css("width", "8em");
            break;

          case "INTEGER":
            cell.css("width", "4em");
            break;
        }
      }

      // So hyperlinks can be styled accordingly
      if (col.type.toUpperCase() == "CODE") {
        cell.attr("data-type", "code");
      }

      // Column background colour
      if (col.backgroundColour) {
        if (type == "th") {
          // Not TH cells
        }
        else {
          cell.css("background-color", col.backgroundColour);
        }
      }

      // Visible?
      if (col.visible) {
        cell.css({ display: "", visibility: "" });
      }
      else {
        cell.css({ display: "none", visibility: "hidden" });
      }

      // Tooltip
      if (col.tooltipText && cell.prop("tagName") == "TH") {
        var tt = $("label.is-tooltip", cell);
        if (tt.length == 0) {
          tt = $("<label class='is-tooltip'>&nbsp;</label>");
          cell.append(tt);

          tt.click(function () {
            widget.UI.MsgBoxInfo(col.tooltipText);
          });
        }
      }
    }

    function PerformBeforeCellUpdate(index, key, newValue, forceRowRefresh) {
      if (mOptions.onBeforeCellUpdate) {
        // Initialise
        var dataRow = mVirtualData[index];
        var cellData = dataRow.cells[key];

        // Create event object
        var e = { row: { listIndex: dataRow.listIndex }, columnKey: key, oldValue: cellData.value, newValue: newValue, refreshRow: false, cancel: false };

        // Call
        try {
          mOptions.onBeforeCellUpdate(e);
        }
        catch (ex) {
          window.alert(ex);
        }

        // Update Cell Data
        if (!e.cancel) {
          cellData.value = newValue;
        }

        // Refresh row (unlike Windows Forms, this is not done automatically; you must set the flag)
        // NOTE: If cancelled or forcing refresh (after edit) then always refresh to restore correct value (assuming data source has not been updated)
        if (e.refreshRow || e.cancel || forceRowRefresh) {
          RefreshRow(dataRow.listIndex);
        }

        // Resize Stick Headers (just in case cell content has changed column width)
        if (mStickyHeaderElement) ResizeStickyHeader();
      }
    }

    // -------------------------------
    // PUBLIC: Perform a Row Drilldown
    // -------------------------------
    function PerformRowDrilldown(index, key) {
      if (mOptions.onRowDrilldown) {
        // Default to Active Row if unspecified
        if (index === undefined) index = mActiveDataRowIndex;

        // Create event object
        var e = { grid: _self, row: { listIndex: index }, columnKey: key };

        // Call
        mOptions.onRowDrilldown(e);
      }
    }

    // ----------------------------------
    // PUBLIC: ActiveColumnIndex property
    // ----------------------------------
    function ActiveColumnIndex(value, holdEvents) {
      if (value === undefined) {
        // Get
        return mActiveColumnIndex;
      }
      else {
        // Set
        // Ensure integer
        value = parseInt(value);
        var lastActiveColumnIndex = mActiveColumnIndex;

        // Clear selected column
        if (mSelectedRowElement) {
          $("td", mSelectedRowElement).removeClass("is-sel");
        }

        // Set active column
        if (value >= 0 && value < mColumns.length) {
          mActiveColumnIndex = value;
          var c = mActiveColumnKey = GetColumnByIndex(mActiveColumnIndex);
          if (c) mActiveColumnKey = c.key; else mActiveColumnKey = "";
          if (mOptions.allowCellSelect) {
            $("td[key='" + mActiveColumnKey + "']", mSelectedRowElement).addClass("is-sel");
          }
        }
        else {
          mActiveColumnIndex = -1;
          mActiveColumnKey = "";
        }
      }
    }

    // -----------------------------------
    // PUBLIC: ActiveDataRowIndex property
    // -----------------------------------
    function ActiveDataRowIndex(value, holdEvents, activatedFromClick, clickedCellColumnKey) {
      if (value === undefined) {
        // Get
        return mActiveDataRowIndex;
      }
      else {
        // Set
        // Ensure integer
        value = parseInt(value);
        var lastActiveDataRowIndex = mActiveDataRowIndex;

        // Clear selected row
        if (mSelectedRowElement) {
          mSelectedRowElement.removeClass("is-sel");
          $("td", mSelectedRowElement).removeClass("is-sel");
          mSelectedRowElement = null;
        }

        // Set selected row
        if (value >= 0 && value < mDataRowElements.length) {
          mActiveDataRowIndex = value;
          mSelectedRowElement = mDataRowElements[mActiveDataRowIndex];
          mSelectedRowElement.addClass("is-sel");

          // Ensure not hidden
          mSelectedRowElement.removeClass("hidden");

          // Show invalid message
          ShowInvalidMessage();
        }
        else {
          mActiveDataRowIndex = -1;
        }

        // Update Active Column
        if (mActiveColumnIndex != -1) ActiveColumnIndex(mActiveColumnIndex);

        // Scroll into view
        ActiveDataRowScrollIntoView();

        // Notify
        if (mOptions.onAfterRowActivate && mActiveDataRowIndex != lastActiveDataRowIndex) {
          if (holdEvents) {
            // Ignore, e.g., after sort
          }
          else {
            if (!clickedCellColumnKey) clickedCellColumnKey = "";
            var e = { row: { listIndex: ActiveDataRowListIndex() }, activatedFromClick: activatedFromClick || false, clickedCellColumnKey: clickedCellColumnKey };
            mOptions.onAfterRowActivate(e);
          }
        }
      }
    }

    // ---------------------------------------
    // PUBLIC: ActiveDataRowListIndex property
    // ---------------------------------------
    function ActiveDataRowListIndex(value, holdEvents) {
      if (value === undefined) {
        // Get
        if (mActiveDataRowIndex == -1 || !mVirtualData || mActiveDataRowIndex >= mVirtualData.length) {
          return -1;
        }
        else {
          return mVirtualData[mActiveDataRowIndex].listIndex;
        }
      }
      else {
        // Set
        mActiveDataRowIndex == -1;
        for (var i = 0; i < mVirtualData.length; i++) {
          if (mVirtualData[i] && mVirtualData[i].listIndex == value) {
            ActiveDataRowIndex(i, holdEvents);
            break;
          }
        }
      }
    }

    // ------------------------------------------
    // PUBLIC: Activate First non-hidden Data Row
    // ------------------------------------------
    function ActivateFirstDataRow(onlyActivateIfNoActiveDataRow) {
      // Skip?
      if (mActiveDataRowIndex != -1 && onlyActivateIfNoActiveDataRow) return;

      // Activate
      if (mVirtualData) {
        var index = -1;

        for (var i = 0; i < mVirtualData.length; i++) {
          if (!mVirtualData[i].hidden) {
            index = i;
            break;
          }
        }

        if (index != -1) ActiveDataRowIndex(index);
      }
    }

    // -----------------------------------------
    // PUBLIC: Activate Last non-hidden Data Row
    // -----------------------------------------
    function ActivateLastDataRow(onlyActivateIfNoActiveDataRow) {
      // Skip?
      if (mActiveDataRowIndex != -1 && onlyActivateIfNoActiveDataRow) return;

      // Activate
      if (mVirtualData) {
        var index = -1;

        for (var i = mVirtualData.length - 1; i >= 0; i--) {
          if (!mVirtualData[i].hidden) {
            index = i;
            break;
          }
        }

        if (index != -1) ActiveDataRowIndex(index);
      }
    }

    // ---------------------------------------------------------------
    // PRIVATE: Move to the previous page based on the active data row
    // ---------------------------------------------------------------
    function ActiveDataRowPageUp() {
      if (mVirtualData && mActiveDataRowIndex > 0) {
        // Get current scroll position and height of scrollable container
        var h = mElement.height();
        var y = mElement.scrollTop;

        // Move down through rows until we find one that is about a page down
        var newRowIndex = mActiveDataRowIndex;
        //TODO:
        newRowIndex -= 10;

        // Update active row
        if (newRowIndex < 0) newRowIndex = 0;
        ActiveDataRowIndex(newRowIndex);

        // Scroll into view
        ActiveDataRowScrollIntoView(true);
      }
    }

    // -----------------------------------------------------------
    // PRIVATE: Move to the next page based on the active data row
    // -----------------------------------------------------------
    function ActiveDataRowPageDown() {
      if (mVirtualData && mActiveDataRowIndex < mVirtualData.length - 1) {
        // Get current scroll position and height of scrollable container
        var h = mElement.height();
        var y = mElement.scrollTop;

        // Move down through rows until we find one that is about a page down
        var newRowIndex = mActiveDataRowIndex;
        //TODO:
        newRowIndex += 10;

        // Update active row
        if (newRowIndex > mVirtualData.length - 1) newRowIndex = mVirtualData.length - 1;
        ActiveDataRowIndex(newRowIndex);

        // Scroll into view
        ActiveDataRowScrollIntoView(true);
      }
    }

    // ----------------------------------------
    // PRIVATE: Move to the next visible column
    // ----------------------------------------
    function ActiveColumnNext() {
      if (mVirtualData && mActiveColumnIndex < mColumns.length - 1) {
        var index = mActiveColumnIndex;
        for (var i = mActiveColumnIndex + 1; i < mColumns.length; i++) {
          if (mColumns[i].visible) {
            index = i;
            break;
          }
        }

        ActiveColumnIndex(index);
      }
    }

    // -----------------------------------------------------------------
    // PRIVATE: Move to the next active data row (bypassing hidden rows)
    // -----------------------------------------------------------------
    function ActiveDataRowNext(addNewRowIfAtBottom) {
      // Add new row?
      if (addNewRowIfAtBottom && mOptions.allowAddRows && !mOptions.readOnly && mVirtualData && mActiveDataRowIndex == mVirtualData.length - 1) {
        AddRow(true);
      }

      if (mVirtualData && mActiveDataRowIndex < mVirtualData.length - 1) {
        var index = mActiveDataRowIndex;
        for (var i = mActiveDataRowIndex + 1; i < mVirtualData.length; i++) {
          if (mVirtualData[i] != null && (mHiddenRowsVisible || !mVirtualData[i].hidden)) {
            index = i;
            break;
          }
        }
        ActiveDataRowIndex(index);

        // Scroll into view
        ActiveDataRowScrollIntoView(true);
      }
    }

    // --------------------------------------------
    // PRIVATE: Move to the previous visible column
    // --------------------------------------------
    function ActiveColumnPrevious() {
      if (mVirtualData && mActiveColumnIndex > 0) {
        var index = mActiveColumnIndex;
        for (var i = mActiveColumnIndex - 1; i >= 0; i--) {
          if (mColumns[i].visible) {
            index = i;
            break;
          }
        }
        ActiveColumnIndex(index);
      }
    }

    // ---------------------------------------------------------------------
    // PRIVATE: Move to the previous active data row (bypassing hidden rows)
    // ---------------------------------------------------------------------
    function ActiveDataRowPrevious() {
      if (mVirtualData && mActiveDataRowIndex > 0) {
        var index = mActiveDataRowIndex;
        for (var i = mActiveDataRowIndex - 1; i >= 0; i--) {
          if (mVirtualData[i] != null && (mHiddenRowsVisible || !mVirtualData[i].hidden)) {
            index = i;
            break;
          }
        }

        ActiveDataRowIndex(index);

        // Scroll into view
        ActiveDataRowScrollIntoView(true);
      }
    }

    // ------------------------------------------
    // PRIVATE: Ensure Active Data Row is visible
    // ------------------------------------------
    function ActiveDataRowScrollIntoView(instant, inViewAmount) {
      // Initialise
      if (instant === undefined) instant = false;

      // Visible?
      if (!mOptions.visible) return;

      // Element to scroll
      var se = mSelectedRowElement;
      if (mTemplateRow && mVirtualData && mActiveDataRowIndex == mVirtualData.length - 1) {
        // Bottom row selected so ensure template row is scrolled into view
        se = mTemplateRow;
      }

      if (se) {
        // Sticky headers overlay the top so ensure row scrolls properly into view
        if (!inViewAmount) inViewAmount = 0;
        if (mOptions.stickyHeader && mStickyHeaderElement) inViewAmount = mStickyHeaderElement.outerHeight();

        // NOTE: This plug-in is at the end of this file
        se.ScrollElementIntoView(instant, instant, { inViewAmount: inViewAmount });
      }
    }

    // ---------------------
    // PUBLIC: Add a new Row
    // ---------------------
    function AddRow(activateNewRow) {
      // Max rows already added?
      if (mNewRowCount >= mOptions.maxNewRows) return false;

      // Validate
      if (mOptions.sortByColumn || mOptions.groupByColumns) {
        window.alert("Sorted or grouped grid do not support adding new rows.");
        return false;
      }

      // Increment count
      mNewRowCount += 1;

      // Notify
      if (mOptions.onRowAdd) {
        // Record original collection size
        var count = mVirtualClass.length;

        // Create event object
        var e = { cancel: false };

        // Call
        mOptions.onRowAdd(e);

        // Cancelled?
        if (e.cancel) return false;

        // Add row
        if (mVirtualClass.length <= count) {
          window.alert("Grid's onRowAdd handler did not add a new item to the collection this grid is bound to.");
          return false;
        }
        else if (mVirtualClass.length != count + 1) {
          window.alert("Grid's onRowAdd handler added multiple rows to the collection this grid is bound to. It should only add a single item.");
          return false;
        }

        // Create table row
        var tr = $("<tr listIndex='" + count + "' class='datarow'></tr>");
        mDataRowElements.push(tr);

        // Add to table (before template row if one exists)
        if (mTemplateRow) {
          tr.insertBefore(mTemplateRow);
        }
        else {
          mElementTBody.append(tr);
        }

        // Create row object for data binding
        var row = CreateRowObject(count);

        // Flag as a new row (used to prevent accidentally creating many new rows from cursor down)
        row.newRow = true;

        // Add to virtual data
        mVirtualData.push(row);

        // Refresh row
        // NOTE: Adding rows should never be used on sortable grids so count should always be both index and listIndex
        RefreshRow_Internal(count, count);

        // Activate
        if (activateNewRow) {
          ActivateLastDataRow(false);
        }

        // Resize Sticky Header
        if (mStickyHeaderElement || mStickyFooterElement) ResizeStickyHeader();
      }
      else {
        window.alert("Grid does not handle onRowAdd.");
        return false;
      }

      return true;
    }

    // -------------------------------------------
    // PUBLIC: Indicates if a new row can be added
    // -------------------------------------------
    function AllowAddRows(value) {
      if (value === undefined) {
        // Get
        return mOptions.allowAddRows;
      }
      else {
        // Set
        mOptions.allowAddRows = (value == true);

        // Update Element
        UpdateElement(true);
      }
    }

    // -------------------------------------
    // PRIVATE: Show a row's Invalid Message
    // -------------------------------------
    function ShowInvalidMessage() {
      var invalidMessage = "";

      if (mActiveDataRowIndex >= 0 && mActiveDataRowIndex < mVirtualData.length) {
        var dataRow = mVirtualData[mActiveDataRowIndex];
        //if (dataRow.invalid && dataRow.invalidMessage && !dataRow.newRow) {
        if (dataRow.invalid && dataRow.invalidMessage) {
          invalidMessage = dataRow.invalidMessage;
        }
      }

      if (invalidMessage) {
        mInvalidMessageElement.text(invalidMessage);
        mInvalidMessageElement.show();

      }
      else {
        mInvalidMessageElement.hide();
      }

      // Ensure Active Row visible
      if (mTemplateRow) {
        ActiveDataRowScrollIntoView(false, mTemplateRow.outerHeight());
      }
      else {
        ActiveDataRowScrollIntoView();
      }
    }

    // ---------------------------------------------------------------------
    // PRIVATE: Create a Row Object (required for behind the scenes binding)
    // ---------------------------------------------------------------------
    function CreateRowObject(listIndex) {
      var cells = {};
      for (var j = 0; j < mColumns.length; j++) {
        // Cell defaults
        cells[mColumns[j].key] = {
          key: mColumns[j].key, // Shortcut to column key
          value: null,          // Cell value
          sortValue: null,      // Optional, sort value
          readOnly: false,      // For editable grids
          notApplicable: false, // Make read-only, hide value and hatch
          //hyperlink: "",      // Allows the cell text to be hyperlinked without having to resort to HTML cell content

          cssClass: null,
          colour: null,
          backgroundColour: null,
          bold: false,
          small: false,
          strike: false,
          tooltipText: "",
          blankTip: "",

          invalid: false,       // When the grid can accept data entry, this can be set to flag the row as invalid
          invalidMessage: "",
        };
      }

      // Create row data and set row defaults
      var row = {
        listIndex: listIndex,
        cells: cells,
        bold: false,
        inactive: false,
        colour: null,
        backgroundColour: null,
        hidden: false,
        readOnly: false,          // For editable grids
        small: false,
        strike: false,
        rowSelectorIcon: "",
        details: "",
      };

      // Add auto-binding ability
      row.AutoBind = function (item) { RowAutoBind(row, item); };
      row.AutoBindTaskManager2UserData = function (item) { RowAutoBindTaskManager2UserData(row, item); };

      return row;
    }

    function RowAutoBind(row, item) {
      for (var p in item) {
        for (var c in row.cells) {
          if (p == c) {
            row.cells[c].value = item[p];
          }
        }
      }
    }

    function RowAutoBindTaskManager2UserData(row, item) {
      if (item.UserData) {
        for (var i = 0; i <= 9; i++) {
          var key = "UserData" + i;

          for (var c in row.cells) {
            if (key == c) {
              row.cells[c].value = item.UserData[i];
            }
          }
        }
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery TABLE Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------------
    // PUBLIC: Export Data
    // -------------------
    function ExportData(format) {
      // Package up displayed data
      var exportData = { columns: [], data: [] };

      // Add visible columns
      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];
        if ((c.visible || c.alwaysExport) && c.excludeFromExport !== true) {
          switch (c.type.toUpperCase()) {
            case "DRILLDOWN":
            //case "HTML":
              // Ignore
              break;

            default:
              var caption = c.caption;
              if (c.exportColumnHeader) caption = c.exportColumnHeader;
              if (caption && caption.toUpperCase().startsWith("<HTML>")) {
                // Prevent issues with insecure requests
                caption = c.key;
              }
              exportData.columns.push({ key: c.key, caption: caption, dataType: c.type });
              break;
          }
        }
      }

      // Add data
      if (mVirtualData) {
        for (var row = 0; row < mVirtualData.length; row++) {
          var r = [];
          var dataRow = mVirtualData[row];

          if (dataRow) {
            exportData.data.push(r);

            for (var i = 0; i < exportData.columns.length; i++) {
              var c = exportData.columns[i];
              var v = dataRow.cells[c.key].value;
              var ve = dataRow.cells[c.key].valueExport;
              if (ve !== undefined) v = ve;

              // Get value from virtual class for HTML etc
              if (c.dataType == "html") {
                v = mVirtualClass[dataRow.listIndex][c.key];
              }

              if (v === undefined) v = null;

              r.push(v);
            }
          }
        }
      }

      // Export
      var params = { gridData: exportData, format: format, exportFileName: mOptions.exportFileName };
      widget._SystemDownloadFile("ExportGridData", params,
        function (data) {
        },

        function (data) {
          widget.RegisterError("widget_grid.ExportData: Failed to export grid data: " + data);
        }
      );
    }

    // ------------------------------------------------------------------------
    // PUBLIC: GroupByColumns property (a comma-separated list of column keys)
    //
    // NOTE:
    // Only a single column is currently supported and this relies on the
    // grid's data already being sorted in the correct order.
    // ------------------------------------------------------------------------
    function GroupByColumns(value) {
      if (value === undefined) {
        // Get
        return mOptions.groupByColumns;
      }
      else {
        // Set
        mOptions.groupByColumns = value;
      }
    }

    // ----------------------------
    // PUBLIC: Read-Only property
    // ----------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement(true);
        }
      }
    }

    // ---------------
    // PUBLIC: Refresh
    // ---------------
    function Refresh(reinitialise) {
      UpdateElement(reinitialise);
    }

    // ------------------------
    // PUBLIC: Show Hidden Rows
    // ------------------------
    function ShowHiddenRows(toggle) {
      if (toggle) {
        mHiddenRowsVisible = !mHiddenRowsVisible;
      }
      else {
        mHiddenRowsVisible = true;
      }

      var els = $("tr.hideable", mElement);
      if (mHiddenRowsVisible) {
        els.removeClass("hidden");
      }
      else {
        els.addClass("hidden");
      }

      // Hidden rows caption
      mCaption_Refresh();

      ActiveDataRowScrollIntoView();

      // Resize Sticky Header
      if (mOptions.stickyHeader) ResizeStickyHeader();
    }

    // ------------------------------------------
    // PRIVATE: Refresh the 'Hidden Rows' Caption
    // ------------------------------------------
    function mCaption_Refresh() {
      if (mCountHidden == 1) {
        if (mHiddenRowsVisible) {
          mCaption = "1 row was hidden";
        }
        else {
          mCaption = "1 row is hidden";
        }
      }
      else {
        if (mHiddenRowsVisible) {
          mCaption = mCountHidden + " rows were hidden";
        }
        else {
          mCaption = mCountHidden + " rows are hidden";
        }
      }
      if (mHiddenRowsVisible) {
        mCaption += ". Click to re-hide.";
      }
      else {
        mCaption += ". Click to show.";
      }
      mCaptionContentElement.text(mCaption);
    }

    // ----------------------------
    // PUBLIC: Virtual Data Refresh
    // ----------------------------
    function VirtualDataRefresh(virtualClass, retainActiveDataRowIndex, options, holdRebuild) {
      // Options
      if (!options) options = {};
      var retainSelectedRows = (options.retainSelectedRows == true);

      // Save current active row and, if necessary, selected rows
      var oldActiveDataRowIndex = mActiveDataRowIndex;
      var oldSelectedRowIndexes = [];
      if (retainSelectedRows) {
        if (mOptions.sortByColumn) {
          // Sorted so must use actual display index
          oldSelectedRowIndexes = [];
          for (var i = 0; i < mVirtualData.length; i++) {
            var row = mVirtualData[i];
            if (!row) {
              // Deleted
            }
            else if (row.rowSelectorCheckBox) {
              if (row.rowSelectorCheckBox.Value()) {
                oldSelectedRowIndexes.push(i);
              }
            }
          }
        }
        else {
          // Not sorted so can use ListIndex
          oldSelectedRowIndexes = GetSelectedRowIndexes(false, false);
        }
      }

      // Set Virtual Data (if supplied)
      if (virtualClass) {
        mVirtualClass = virtualClass;
      }
      mVirtualData = [];

      // Any Columns?
      if (mColumns.length == 0) return;

      // Initialise
      //mHiddenRowsVisible = false;
      mNewRowCount = 0;

      // Validate
      if (!mOptions.onInitialiseRow) {
        window.alert("widet.UI.Grid.VirtualDataRefresh: options.onInitialiseRow handler not specified.");
      }
      // Allow virtual binding (ignore items in virtual class that have been deleted, i.e., flagged as null rather than removed from the collection)
      try {
        for (var i = 0; i < mVirtualClass.length; i++) {
          if (mVirtualClass[i] != null) {
            // Create row object for data binding
            var row = CreateRowObject(i);

            // Create event object
            var e = { row: row, grid: _self };

            // Add to virtual data
            mVirtualData.push(row);

            // Call
            mOptions.onInitialiseRow(e);
          }
        }
      }
      catch (ex) {
        window.alert("widget.UI.Grid.VirtualDataRefresh: " + ex.message);
      }

      // Refresh layout
      if (!holdRebuild) {
        try {
          Refresh(true);
        }
        catch (ex) {
          // Out of memory or jQuery stack issues may occur with huge data-sets
          window.alert("The following error occurred attempting to refresh this grid:\n\n" + ex);
        }
      }

      // Restore Active Data Row Index
      if (retainActiveDataRowIndex) {
        ActiveDataRowIndex(-2);
        ActiveDataRowIndex(oldActiveDataRowIndex);
      }
      else {
        ActiveDataRowIndex(-1);

        // Notify
        if (mOptions.onAfterRowActivate) {
          var e2 = { row: { listIndex: ActiveDataRowListIndex() }, activatedFromClick: false };
          mOptions.onAfterRowActivate(e2);
        }
      }

      // Showing hidden rows?
      if (mHiddenRowsVisible) {
        ShowHiddenRows(false);
      }

      // Restore Selected Rows
      if (retainSelectedRows) {
        if (mOptions.sortByColumn) {
          SetSelectedRowIndexesForSortableGrid(oldSelectedRowIndexes, true);
        }
        else {
          SetSelectedRowIndexes(oldSelectedRowIndexes, true);
        }
      }

      // Initialise filter TextBox
      if (mTxtSearch) {
        mTxtSearch.Initialise($("table", mWrapperElement));
        if (mOptions.customFilterMessage) {
          mTxtSearch.BlankTip(mOptions.customFilterMessage);
        }
        else {
          mTxtSearch.BlankTip("Type to filter list (" + mVirtualData.length + " items)");
        }
      }
    }

    // ---------------------------------------------------
    // PUBLIC: Refresh a row with the specified list index
    // ---------------------------------------------------
    function RefreshRow(listIndex, index) {
      // Locate Index from List Index
      if (index === undefined) {
        for (var i = 0; i < mVirtualData.length; i++) {
          if (mVirtualData[i].listIndex == listIndex) {
            index = i;
            break;
          }
        }
      }
      RefreshRow_Internal(listIndex, index);

      // Refresh cell active state
      if (mOptions.allowCellSelect) ActiveColumnIndex(mActiveColumnIndex);
    }

    function RefreshRow_Internal(listIndex, index) {
      // Create event object
      var e = { row: mVirtualData[index] };

      // Re-fetch data
      mOptions.onInitialiseRow(e);

      // Locate table row
      var row = $("tr[listindex=" + listIndex + "]", mElementTBody);

      // Save current hidden state
      var oldHidden = row.hasClass("hidden");

      // Update grid row data
      RefreshRow_UpdateData(index, row, true);

      // Ensure row has not just been hidden
      if (!oldHidden) row.removeClass("hidden hideable");

      // Show invalid message
      ShowInvalidMessage();
    }


    // -------------------------------------------------------------------
    // PUBLIC: Remove a grid row AND the item in the underlying collection
    // -------------------------------------------------------------------
    function RemoveRowAndCollectionItem(listIndex) {
      if (listIndex < 0 || listIndex > mVirtualClass.length - 1) {
        console.warn("widget_ui.Grid.RemoveRowAndCollectionItem: listIndex is outside of the bounds of the virtual class.");
        return false;
      }

      // Decrement added new rows?
      // NOTE: newRow = false after the new row has been edited; it is still a new row!
      if (mVirtualData[listIndex].newRow == true || mVirtualData[listIndex].newRow == false) {
        mNewRowCount -= 1;
      }

      // Clear selected row
      if (listIndex == mActiveDataRowIndex) mSelectedRowElement = null;

      // Remove grid row
      var dre = mDataRowElements[listIndex];
      widget.ArrayRemove(mDataRowElements, mDataRowElements[listIndex]);
      dre.remove();
      widget.ArrayRemove(mVirtualData, mVirtualData[listIndex]);

      // Remove from collection
      widget.ArrayRemove(mVirtualClass, mVirtualClass[listIndex]);

      // Update Row Counts and list indexes
      for (var i = 0; i < mDataRowElements.length; i++) {
        var dr = mDataRowElements[i];
        dr.attr("listIndex", i);
        mVirtualData[i].listIndex = i;

        if (mOptions.rowNumbering) {
          var rs = $("td.rowselector span.rownumber", dr);
          rs.text(i + 1);
        }
      }

      // Update Active Row
      if (mActiveDataRowIndex != -1 && listIndex <= mActiveDataRowIndex) {
        var i = mActiveDataRowIndex;
        if (i < 0) i = 0;
        if (i > mVirtualData.length - 1) i = mVirtualData.length - 1;
        ActiveDataRowIndex(i);
      }

      return true;
    }

    // ----------------------------------------------------------------------------
    // PUBLIC: Remove selected grid rows AND the items in the underlying collection
    // ----------------------------------------------------------------------------
    function RemoveSelectedRowsAndCollectionItems() {
      // Get selected row indexes
      var indexes = GetSelectedRowIndexes(true);

      // Remove in reverse order
      for (var i = indexes.length - 1; i >= 0; i--) {
        RemoveRowAndCollectionItem(indexes[i]);
      }
    }

    // --------------------------------------------------------
    // PUBLIC: Move active row up in the Grid and Virtual Class
    // --------------------------------------------------------
    function RowMoveUp() {
      // Can Row move?
      if (!CanRowMoveUp()) return;

      // Swap Rows (including list indexes and mDataRowElements array)
      // NOTE: Since row moving should never occur in sortable grids, ActiveDataRowIndex and ActiveDataRowListIndex are the same
      var row = $("tr[listIndex='" + mActiveDataRowIndex + "']", mElementTBody);
      var rowOther = row.prev();
      rowOther.before(row);
      row.attr("listIndex", mActiveDataRowIndex - 1);
      rowOther.attr("listIndex", mActiveDataRowIndex);

      row = mDataRowElements[mActiveDataRowIndex];
      rowOther = mDataRowElements[mActiveDataRowIndex - 1];
      mDataRowElements[mActiveDataRowIndex] = rowOther;
      mDataRowElements[mActiveDataRowIndex - 1] = row;

      // Swap entries in Virtual Class
      row = mVirtualClass[mActiveDataRowIndex];
      rowOther = mVirtualClass[mActiveDataRowIndex - 1];
      mVirtualClass[mActiveDataRowIndex] = rowOther;
      mVirtualClass[mActiveDataRowIndex - 1] = row;

      row = mVirtualData[mActiveDataRowIndex];
      rowOther = mVirtualData[mActiveDataRowIndex - 1];
      mVirtualData[mActiveDataRowIndex] = rowOther;
      mVirtualData[mActiveDataRowIndex - 1] = row;

      // Update list indexes (for ActiveDataRowListIndex property)
      row.listIndex = mActiveDataRowIndex - 1;
      rowOther.listIndex = mActiveDataRowIndex;

      // Decrement Active Row
      ActiveDataRowIndex(mActiveDataRowIndex - 1);

      // Update Buttons
      RefreshButtons();
    }

    function CanRowMoveUp() {
      if (mActiveDataRowIndex < 1 || mActiveDataRowIndex >= mVirtualClass.length) return false;
      if (mActiveDataRowIndex == 0) return false;      

      // Custom Group By
      if (mCustomGroupByOrder) {
        widget.UI.MsgBoxAlert("Rows cannot be moved within Grids which use a Custom Group By Order.");
        return false;
      }

      // Sortable grids cannot have rows moved (see comment in RowMoveUp())
      for (var i = 0; i < mColumns.length; i++) {
        // Get Column
        var col = mColumns[i];

        if (col.sortable) {
          widget.UI.MsgBoxAlert("Rows cannot be moved within Sortable Grids.");
          return false;
        }
      }

      // Must check this after all return false conditions are checked
      if (!mOptions.groupByColumns) return true;

      // Rows Grouped, ensure start of group hasn't been reached
      var thisItem = mVirtualData[mActiveDataRowIndex].cells[mOptions.groupByColumns].value;
      var previousItem = mVirtualData[mActiveDataRowIndex - 1].cells[mOptions.groupByColumns].value;

      return (thisItem == previousItem);
    }

    // ----------------------------------------------------------
    // PUBLIC: Move active row down in the Grid and Virtual Class
    // ----------------------------------------------------------
    function RowMoveDown() {
      // Can Row move?      
      if (!CanRowMoveDown()) return;

      // Swap Rows (including list indexes and mDataRowElements array)
      // NOTE: Since row moving should never occur in sortable grids, ActiveDataRowIndex and ActiveDataRowListIndex are the same
      var row = $("tr[listIndex='" + mActiveDataRowIndex + "']", mElementTBody);
      var rowOther = row.next();
      rowOther.after(row);

      row.attr("listIndex", mActiveDataRowIndex + 1);
      rowOther.attr("listIndex", mActiveDataRowIndex);

      row = mDataRowElements[mActiveDataRowIndex];
      rowOther = mDataRowElements[mActiveDataRowIndex + 1];
      mDataRowElements[mActiveDataRowIndex] = rowOther;
      mDataRowElements[mActiveDataRowIndex + 1] = row;

      // Swap entries in Virtual Class
      row = mVirtualClass[mActiveDataRowIndex];
      rowOther = mVirtualClass[mActiveDataRowIndex + 1];
      mVirtualClass[mActiveDataRowIndex] = rowOther;
      mVirtualClass[mActiveDataRowIndex + 1] = row;

      row = mVirtualData[mActiveDataRowIndex];
      rowOther = mVirtualData[mActiveDataRowIndex + 1];
      mVirtualData[mActiveDataRowIndex] = rowOther;
      mVirtualData[mActiveDataRowIndex + 1] = row;

      // Update list indexes (for ActiveDataRowListIndex property)
      row.listIndex = mActiveDataRowIndex + 1;
      rowOther.listIndex = mActiveDataRowIndex;

      // Increment Active Row
      ActiveDataRowIndex(mActiveDataRowIndex + 1);

      // Update Buttons
      RefreshButtons();
    }

    function CanRowMoveDown() {
      if (mActiveDataRowIndex < 0 || mActiveDataRowIndex >= mVirtualClass.length - 1) return false;
      if (mActiveDataRowIndex >= mVirtualData.length) return false;      

      // Custom Group By
      if (mCustomGroupByOrder) {
        widget.UI.MsgBoxAlert("Rows cannot be moved within Grids which use a Custom Group By Order.");
        return false;
      }

      // Sortable grids cannot have rows moved (see comment in RowMoveDown())
      for (var i = 0; i < mColumns.length; i++) {
        // Get Column
        var col = mColumns[i];

        if (col.sortable) {
          widget.UI.MsgBoxAlert("Rows cannot be moved within Sortable Grids.");
          return false;
        }
      }

      // Must check this after all return false conditions are checked
      if (!mOptions.groupByColumns) return true;

      // Rows Grouped, ensure end of group hasn't been reached
      var thisItem = mVirtualData[mActiveDataRowIndex].cells[mOptions.groupByColumns].value;
      var nextItem = mVirtualData[mActiveDataRowIndex + 1].cells[mOptions.groupByColumns].value;

      return (thisItem == nextItem);
    }

    // --------------------
    // PUBLIC: Clear Search
    // --------------------
    function SearchClear() {
      if (mTxtSearch) {
        mTxtSearch.Text("");
        mTxtSearch.ReapplyFilter();

        // Scroll into view
        ActiveDataRowScrollIntoView();
      }
    }

    // -------------------------------
    // PUBLIC: Get the Selected column
    // -------------------------------
    function SelectedColumn() {
      for (var i = 0; i < mColumns.length; i++) {
        if (mColumns[i].key.toUpperCase() == mOptions.selectedColumnKey.toUpperCase()) {
          return mColumns[i];
        }
      }

      return null;
    }

    // -----------------------
    // PUBLIC: Selected column
    // -----------------------
    function SelectedColumnKey(key) {
      if (key === undefined) {
        // Get
        return mOptions.selectedColumnKey;
      }
      else {
        // Set
        // Initialise
        var oldKey = mOptions.selectedColumnKey;
        mOptions.selectedColumnKey = key;
        $("th,td", mElement).removeClass("selected");
        if (mStickyHeaderElement) $("th,td", mStickyHeaderElement).removeClass("selected");

        // Update (without refetch)
        var e = $("th[key='" + mOptions.selectedColumnKey + "'],td[key='" + mOptions.selectedColumnKey + "']", mElement);
        e.addClass("selected");
        if (mStickyHeaderElement) {
          var she = $("th[key='" + mOptions.selectedColumnKey + "'],td[key='" + mOptions.selectedColumnKey + "']", mStickyHeaderElement);
          she.addClass("selected");
        }

        // Notify
        if (mOptions.onColumnSelect && mOptions.selectedColumnKey != oldKey) {
          mOptions.onColumnSelect();
        }
      }
    }

    // ----------------------------------------------------------------------------------------
    // PUBLIC: Set a Column's CSV, i.e., the 'listCsv' option passed in when the Column was defined
    // ----------------------------------------------------------------------------------------
    function SetColumnListCsv(key, listCsv, listMulti) {
      var column = GetColumnByKey(key);

      if (column) {
        column.list = null;
        column.collection = null;
        column._collection = null;

        column.listMulti = (listMulti || false);
        column.listCsv = listCsv;
      }
      else {
        console.warn("widget_ui.Grid.SetColumnListCsv: column '" + key + "' not found.");
      }
    }

    // ----------------------------------------------------------------------------------------------------------------------
    // PUBLIC: Set a Column's Collection, i.e., the 'collection' and associated options passed in when the Column was defined
    // ----------------------------------------------------------------------------------------------------------------------
    function SetColumnCollection(key, collection, idColumn, columns) {
      var column = GetColumnByKey(key);

      if (column) {
        column.listCsv = null;
        column.list = null;

        column.collection = collection;
        column.idColumn = idColumn;
        column.columns = columns;

        column._collection = {};
        column._collection.data = column.collection;
        column._collection.idColumn = column.idColumn;
        column._collection.displayColumns = column.columns;
      }
      else {
        console.warn("widget_ui.Grid.SetColumnCollection: column '" + key + "' not found.");
      }
    }

    // -----------------------------------------------
    // PUBLIC: Get Columns List (cloned, just in case)
    // -----------------------------------------------
    function GetColumnsList(excludeIcon) {
      var arr = [];

      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];
        var include = true;

        // Exclude?
        switch (c.type) {
          case "Icon":
            if (excludeIcon) include = false;
            break;
        }

        // Add (cloned)
        if (include) arr.push(JSON.parse(JSON.stringify(c)));
      }

      return arr;
    }

    // ------------------------------------------------------------------------------------------
    // PUBLIC: Set a Column's List, i.e., the 'list' option passed in when the Column was defined
    // ------------------------------------------------------------------------------------------
    function SetColumnList(key, list, idColumn, columns) {
      var column = GetColumnByKey(key);

      if (column) {
        if (list == column.list) {
          // Unchanged
        }
        else {
          // Update Column
          column.list = list;
          if (idColumn) column.isColumn = idColumn;
          if (columns) column.columns = columns;

          // Fetch (with caching)
          ColumnFetchList(column);
        }
      }
      else {
        console.warn("widget_ui.Grid.SetColumnList: column '" + key + "' not found.");
      }
    }

    // ------------
    // PUBLIC: Sort
    // ------------
    function Sort(key, descending, holdEvents) {
      // Just in case!
      if (!mVirtualData) return;

      // Track currently filtered out rows (either by an attached TableFilterTextBox or by the grids inbuilt filter box)
      var filteredOutItems = [];
      if (mDataRowElements) {
        for (var i = 0; i < mDataRowElements.length; i++) {
          if (mDataRowElements[i].hasClass("is-filtered-out")) {
            filteredOutItems.push(mDataRowElements[i].attr("listIndex"));
          }
        }
      }

      // Get current list index
      var listIndex = ActiveDataRowListIndex();

      if (key) {
        // Sort
        if (descending === undefined && key == mOptions.sortByColumn) {
          // Toggle
          mOptions.sortByDesc = !mOptions.sortByDesc;
        }
        else {
          // Sort
          mOptions.sortByColumn = key;
          mOptions.sortByDesc = descending;
        }
      }
      else {
        // Clear sorting
        mOptions.sortByColumn = "";
        mOptions.sortByDesc = false;
      }

      // Account for sorting group column
      if (!mOptions.sortByColumn) {
        // Ensure groupings are preserved after clearing sort (J031428)
        GroupByColumnsUpdate(mOptions.groupByColumns, { virtualDataRefresh: true });
      }
      else if (mOptions.sortByColumn && mOptions.sortByColumn == mOptions.groupByColumns) {
        if (mOptions.sortByDesc) {
          mOptions.groupByOrder = "DESC";
        }
        else {
          mOptions.groupByOrder = "ASC";
        }
      }

      // Update
      // NOTE: Special flag to ensure that hidden row visible state is preserved
      UpdateElement(false, true);

      // Restore list index
      ActiveDataRowListIndex(listIndex, true);

      // Replay filtered out rows
      if (filteredOutItems.length != 0) {
        for (var i = 0; i < mDataRowElements.length; i++) {
          var listIndex = mDataRowElements[i].attr("listIndex");
          if (filteredOutItems.indexOf(listIndex) != -1) {
            mDataRowElements[i].addClass("is-filtered-out");
          }
        }
      }

      // Notify
      if (!holdEvents && mOptions.onAfterColumnSort) mOptions.onAfterColumnSort();
    }

    // -------------------------------------------------------------
    // PUBLIC: Set Column's Visibility (must refresh grid to redraw)
    // -------------------------------------------------------------
    function ColumnVisible(key, visible) {
      key = key.toUpperCase();

      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];
        if (c.key.toUpperCase() == key) {
          c.visible = visible;

          // Hide existing headings so they don't appear before grid is refreshed
          if (c.thElement && !visible) {
            c.thElement.hide();
          }
          break;
        }
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        if (mOptions.visible) {
          mWrapperElement.show();
        }
        else {
          mWrapperElement.hide();
        }
      }
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
    }

    // -----------------------------------
    // PUBLIC: Select or unselect all Rows
    // -----------------------------------
    function SelectAllRows(select, excludeHiddenRows) {
      if (mOptions.allowMultiRowSelect) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var row = mVirtualData[i];
          if (row && row.rowSelectorCheckBox) {
            var tr = mDataRowElements[row.listIndex];

            if (excludeHiddenRows && tr.hasClass("is-filtered-out")) {
              // Ignore filtered out rows
            }
            else {
              row.rowSelectorCheckBox.Value(select);
              if (select) {
                tr.addClass("row-selected");
              }
              else {
                tr.removeClass("row-selected");
              }
            }
          }
        }

        // Update select all/ none checkbox
        mElementSelectUnselect.Value(select);

        // Notify (e.g., so that action buttons can be updated)
        // NOTE: Should probably do a different event but this is OK for now
        if (mOptions.onAfterRowActivate) {
          var e2 = { row: { listIndex: ActiveDataRowListIndex() }, activatedFromClick: false };
          mOptions.onAfterRowActivate(e2);
        }

        // Update caption
        mSelectedRowCountElement_Refresh();

        // Notify
        if (mOptions.onSelectedRowsChanged) {
          mOptions.onSelectedRowsChanged({});
        }
      }
    }

    // -----------------------------------
    // PRIVATE: Updated selected row count
    // -----------------------------------
    function mSelectedRowCountElement_Refresh() {
      var count = GetSelectedRowIndexes(false).length;
      if (count == 0) {
        mSelectedRowCountElement.hide();
      }
      else {
        switch (count) {
          case 1:
            mSelectedRowCountElement.text("1 row selected");
            break;

          default:
            mSelectedRowCountElement.text(count + " rows selected");
            break;
        }
        mSelectedRowCountElement.show();
        mSelectedRowCountElement.css("display", "inline-block");
        var pos = mTableWrapper.offset();
        mSelectedRowCountElement.css("left", (pos.left + 20) + "px")
      }
    }

    // -------------------------------------------------------------------
    // PUBLIC: Get an array containing unique details of all selected rows
    // -------------------------------------------------------------------
    function GetSelectedRowDetailsFromUniqueProperty(propertyName, defaultActiveRow, ignoreExpiredRows) {
      var rows = [];

      // Get selected rows
      if (mOptions.allowMultiRowSelect) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var row = mVirtualData[i];
          if (!row) {
            // Deleted
          }
          else if (row.rowSelectorCheckBox) {
            if (row.rowSelectorCheckBox.Value()) {
              if (!ignoreExpiredRows || !row.expired) {
                rows.push({ value: mVirtualClass[row.listIndex][propertyName], selected: true, listIndex: row.listIndex });
              }
            }
          }
        }
      }

      // Add Active Row List Index?
      var activeDataRowListIndex = ActiveDataRowListIndex();
      if (defaultActiveRow && rows.length == 0 && activeDataRowListIndex >= 0) {
        if (!ignoreExpiredRows || !mVirtualData[activeDataRowListIndex].expired) {
          // Active row, i.e., not selected
          rows.push({ value: mVirtualClass[activeDataRowListIndex][propertyName], selected: false, listIndex: activeDataRowListIndex });
        }
      }

      return rows;
    }

    // ----------------------------------------------------------------------------------
    // PUBLIC: Set selected rows from an array containing unique details of selected rows
    // ----------------------------------------------------------------------------------
    function SetSelectedRowDetailsFromUniqueProperty(propertyName, array, clearExisting) {
      // Clear existing?
      if (clearExisting) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var row = mVirtualData[i];
          if (row && row.rowSelectorCheckBox) {
            row.rowSelectorCheckBox.Value(false);
            mDataRowElements[row.listIndex].removeClass("row-selected");
          }
        }
      }

      // Select rows
      var activeRowListIndex = -1;
      for (var i = 0; i < mVirtualData.length; i++) {
        var dataRow = mVirtualData[i];
        var item = mVirtualClass[dataRow.listIndex];
        var propertyValue = item[propertyName];

        for (var j = 0; j < array.length; j++) {
          var row = array[j];

          if (row.value == propertyValue) {
            if (row.selected) {
              // Select
              if (dataRow.rowSelectorCheckBox) dataRow.rowSelectorCheckBox.Value(true);
              mDataRowElements[i].addClass("row-selected");

              // Activate this row (by default)
              if (activeRowListIndex == -1) activeRowListIndex = dataRow.listIndex;
            }
            else {
              // Activate (in next block)
              activeRowListIndex = dataRow.listIndex;
            }

            // Found
            break;
          }
        }
      }

      // Active row?
      if (activeRowListIndex != -1 || clearExisting) {
        ActiveDataRowListIndex(activeRowListIndex);
      }

      // Update caption
      mSelectedRowCountElement_Refresh();
    }

    // ---------------------------------------------------------------------
    // PUBLIC: Get an array containing the list indexes of all selected rows
    // ---------------------------------------------------------------------
    function GetSelectedRowIndexes(defaultActiveRow, ignoreExpiredRows) {
      var rows = [];

      // Get selected rows
      if (mOptions.allowMultiRowSelect) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var row = mVirtualData[i];
          if (!row) {
            // Deleted
          }
          else if (row.rowSelectorCheckBox) {
            if (row.rowSelectorCheckBox.Value()) {
              if (!ignoreExpiredRows || !row.expired) {
                rows.push(row.listIndex);
              }
            }
          }
        }
      }

      // Add Active Row List Index?
      var activeDataRowListIndex = ActiveDataRowListIndex();
      if (defaultActiveRow && rows.length == 0 && activeDataRowListIndex >= 0) {
        if (!ignoreExpiredRows || !mVirtualData[activeDataRowListIndex].expired) {
          rows.push(activeDataRowListIndex);
        }
      }

      return rows;
    }

    // -----------------------------------------------------------
    // PUBLIC: Select rows from the supplied array of List Indexes
    // -----------------------------------------------------------
    function SetSelectedRowIndexes(indexes, clearExisting) {
      // Clear existing?
      if (clearExisting) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var row = mVirtualData[i];
          if (row && row.rowSelectorCheckBox) {
            row.rowSelectorCheckBox.Value(false);
            mDataRowElements[row.listIndex].removeClass("row-selected");
          }
        }
      }

      // Warning (J030714)
      if (mOptions.sortByColumn) {
        console.warn("widget.UI.Grid.SetSelectedRowIndexes: This method is known to have issues with sorted grids. Use SetSelectedRowIndexesForSortableGrid passing in an array of row indexes instead of list indexes instead");
      }

      // Unsorted
      for (var i = 0; i < indexes.length; i++) {
        var row = mVirtualData[indexes[i]];
        if (row && row.rowSelectorCheckBox) {
          row.rowSelectorCheckBox.Value(true);
          mDataRowElements[row.listIndex].addClass("row-selected");
        }
      }

      // Update caption
      mSelectedRowCountElement_Refresh();
    }

    // ----------------------------------------------------------------------------------------------------
    // PUBLIC: Select rows from the supplied array of Row Indexes which may be necessary for Sortable Grids
    // ----------------------------------------------------------------------------------------------------
    function SetSelectedRowIndexesForSortableGrid(indexes, clearExisting) {
      // Clear existing?
      if (clearExisting) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var row = mVirtualData[i];
          if (row && row.rowSelectorCheckBox) {
            row.rowSelectorCheckBox.Value(false);
            mDataRowElements[row.listIndex].removeClass("row-selected");
          }
        }
      }

      // Select
      for (var i = 0; i < indexes.length; i++) {
        var row = mVirtualData[indexes[i]];
        if (row && row.rowSelectorCheckBox) {
          row.rowSelectorCheckBox.Value(true);
          mDataRowElements[indexes[i]].addClass("row-selected");
        }
      }

      // Update caption
      mSelectedRowCountElement_Refresh();
    }

    // -------------------------------------------------------------------------------------------------------------
    // PUBLIC: Select rows from the supplied array of Virtual Data Indexes which may be necessary for Sortable Grids
    // -------------------------------------------------------------------------------------------------------------
    function SetSelectedVirtualDataRowIndexesForSortableGrid(indexes, clearExisting) {
      // Clear existing?
      if (clearExisting) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var row = mVirtualData[i];
          if (row && row.rowSelectorCheckBox) {
            row.rowSelectorCheckBox.Value(false);
            mDataRowElements[row.listIndex].removeClass("row-selected");
          }
        }
      }

      // Select
      for (var i = 0; i < indexes.length; i++) {
        var row = null;

        // Find the row based upon the List Index
        for (var j = 0; j < mVirtualData.length; j++) {
          var item = mVirtualData[j];

          if (item.listIndex == indexes[i]) {
            row = item;
            break;
          }
        }
          
        // Check and highlight row
        if (row && row.rowSelectorCheckBox) {
          // Check row
          row.rowSelectorCheckBox.Value(true);

          // Highlight row
          for (var j = 0; j < mDataRowElements.length; j++) {
            var item = mDataRowElements[j];

            if (item.attr("listIndex") == row.listIndex) {
              item.addClass("row-selected");
              break;
            }
          }
        }        
      }

      // Update caption
      mSelectedRowCountElement_Refresh();
    }

    // --------------------------------------------------------------
    // PUBLIC: Set the row selector icon and optionally expire the row
    // --------------------------------------------------------------
    function SetRowSelectorIcon(listIndex, icon, details, options) {
      // Locate row
      var row;
      var rowIndex;
      for (var i = 0; i < mVirtualData.length; i++) {
        if (mVirtualData[i].listIndex == listIndex) {
          row = mVirtualData[i];
          rowIndex = i;
          break;
        }
      }
      if (!row) return;

      // Set row details
      row.rowSelectorIcon = icon;
      if (details !== undefined) row.details = details;

      // Other options
      if (options) {
        if (options.rowExpired !== undefined) row.expired = options.rowExpired;
      }

      // Refresh row
      RefreshRow(listIndex, rowIndex);
    }

    // ---------------------------------------------------------------------------------------------------------
    // PUBLIC: Get a filtered array of Virtual Data records based on Selected Rows and in the current sort order
    // ---------------------------------------------------------------------------------------------------------
    function GetVirtualDataForSelectedRows(returnAllIfNoSelectedRows) {
      // Initialise
      if (returnAllIfNoSelectedRows === undefined) returnAllIfNoSelectedRows = false;
      var records = [];

      if (mVirtualClass) {
        var selectedRowIndexes = GetSelectedRowIndexes(false, false);

        for (var i = 0; i < mVirtualData.length; i++) {
          var dataRow = mVirtualData[i];

          if ((returnAllIfNoSelectedRows && selectedRowIndexes.length == 0) || selectedRowIndexes.indexOf(dataRow.listIndex) != -1) {
            var item = mVirtualClass[dataRow.listIndex];
            records.push(item);
          }
        }

        //for (var i = 0; i < mVirtualClass.length; i++) {
        //  if ((returnAllIfNoSelectedRows && selectedRowIndexes.length == 0) || selectedRowIndexes.indexOf(i) != -1) {
        //    records.push(mVirtualClass[i]);
        //  }
        //}
      }

      return records;
    }

    // =============================================================================
    // PUBLIC: Update Group By Columns and optionally perform a Virtual Data Refresh
    // =============================================================================
    function GroupByColumnsUpdate(groupByColumns, options) {
      // Update options
      var o = $.extend({}, {
        descending: undefined,
        groupingsCollapsed: false,
        virtualDataRefresh: false
      }, options);

      mOptions.groupByColumns = groupByColumns;
      mOptions.sortByColumn = groupByColumns;
      mOptions.groupingsCollapsed = o.groupingsCollapsed;
      if (o.descending != undefined) {
        mOptions.groupByDesc = o.descending;
        mOptions.sortByDesc = o.descending;
      }

      if (o.virtualDataRefresh) VirtualDataRefresh(mVirtualClass, true);
    }

    // --------------------------------------------------
    // PUBLIC: Validate (based on row invalid properties)
    // --------------------------------------------------
    function Validate() {
      // Initialise
      var valid = true;

      // Check for invalid rows
      if (mVirtualData) {
        for (var i = 0; i < mVirtualData.length; i++) {
          var dataRow = mVirtualData[i];

          if (dataRow.invalid) {
            ActiveDataRowIndex(i);
            valid = false;
            break;
          }
        }
      }

      return valid;
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function ResizeFromParent() {
      mElement.css({ width: "100%", height: "100%", overflow: "auto" });
      //UpdateAutoHideColumns();
    }

    // --------------------------------
    // PUBLIC: Column's Heading Caption
    // --------------------------------
    function ColumnCaption(key, caption) {
      key = key.toUpperCase();

      for (var i = 0; i < mColumns.length; i++) {
        var c = mColumns[i];
        if (c.key.toUpperCase() == key) {
          c.caption = caption;

          // Update heading
          if (c.thElement) {
            if (c.caption.substr(0, 6).toUpperCase() == "<HTML>") {
              c.thElement.html(c.caption.substr(6));
            }
            else {
              c.thElement.text(c.caption);
            }
          }
          break;
        }
      }
    }

    // --------------------------------------------------------
    // PUBLIC: Get the Virtual Class that this grid is bound to
    // --------------------------------------------------------
    function GetVirtualClass() {
      return mVirtualClass;
    }

    // -----------------------------------------------------
    // PUBLIC: Get the Key of the Column for the Active Cell
    // -----------------------------------------------------
    function ActiveCellColumnKey() {
      if (mActiveDataRowListIndex == -1) {
        return "";
      }
      else {
        var els = $("td.is-sel", mElement);
        window.alert(els.length);

        if (els.length == 0) {
          return "";
        }
        else {
          return "x";
        }
      }
    }

    // ------------------------------------------------------------------------------
    // FRIEND: Get column data for Pie Chart visualisation (values and labels arrays)
    // ------------------------------------------------------------------------------
    function GetColumnDataForPieChart(labelColumnKey, valueColumnKey, excludeNone, sort) {
      var values = [];
      var labels = [];
      var columnValue = GetColumnByKey(valueColumnKey);
      var hasNone = false;

      if (columnValue) {
        // Get unique labels
        for (var i = 0; i < mVirtualClass.length; i++) {
          var item = mVirtualClass[i];
          var label;

          if (labelColumnKey.startsWith("UserData") && item.UserData) {
            label = "" + item["UserData"][parseInt(labelColumnKey.substr(8))];
          }
          else {
            label = item[labelColumnKey];
            if (label === undefined || label === null) {
              label = "";
            }
            else {
              label = "" + label;
            }
          }

          if (!label && !excludeNone) {
            hasNone = true;
            label = "[None]";
          }
          if (label && labels.indexOf(widget.UI.HtmlEncode(label)) == -1) {
            labels.push(widget.UI.HtmlEncode(label));

            // Sum values/ count (depending on column type)
            var value = 0;
            for (var j = 0; j < mVirtualClass.length; j++) {
              var item2 = mVirtualClass[j];
              var labelValue = item2[labelColumnKey];
              var valueValue = item2[valueColumnKey];

              if (labelColumnKey.startsWith("UserData") && item2.UserData) {
                labelValue = "" + item2["UserData"][parseInt(labelColumnKey.substr(8))];
              }
              if (valueColumnKey.startsWith("UserData") && item2.UserData) {
                valueValue = item2["UserData"][parseInt(valueColumnKey.substr(8))];
              }

              if (!labelValue) {
                labelValue = "[None]";
              }

              if (labelValue == label) {
                switch (columnValue.type) {
                  case "ColourFlag":
                    value += 1;
                    break;

                  case "Currency":
                  case "Double":
                    if (labelColumnKey == valueColumnKey) {
                      value += 1;
                    }
                    else {
                      if (valueValue) value += parseFloat(valueValue);
                    }
                    break;

                  case "Integer":
                    if (labelColumnKey == valueColumnKey) {
                      value += 1;
                    }
                    else {
                      if (valueValue) value += parseInt(valueValue);
                    }
                    break;

                  default:
                    value += 1;
                    break;
                }
              }
            }
            if (!value) value = 0; // Just in case null, undefined
            values.push(value);
          }
        }
      }

      // Sort (yes, it's a bubble sort - to keep the 2 arrays in sync)?
      // NOTE: Also handles moving '[None]' to the top
      if (labels.length > 1) {
        var done = false;
        while (!done) {
          done = true;

          for (var i = 1; i < labels.length; i++) {
            var la = labels[i - 1];
            var va = values[i - 1];
            var lb = labels[i];
            var vb = values[i];

            if (lb == "[None]" || (sort && la.toUpperCase() > lb.toUpperCase() && la != "[None]")) {
              // Swap
              labels[i - 1] = lb;
              labels[i] = la;
              values[i - 1] = vb;
              values[i] = va;

              // Carry on
              done = false;
            }
          }
        }
      }

      return { values: values, labels: labels };
    }

    // -------------------------------
    // PUBLIC: ExportFileName property
    // -------------------------------
    function ExportFileName(value) {
      if (value === undefined) {
        // Get
        return mOptions.exportFileName;
      }
      else {
        // Set
        mOptions.exportFileName = value;
      }
    }

    // --------------------------------------
    // PUBLIC: Custom Filter Message property
    // --------------------------------------
    function CustomFilterMessage(value) {
      if (value === undefined) {
        // Get
        return mOptions.customFilterMessage;
      }
      else {
        // Set
        if (value != mOptions.customFilterMessage) {
          mOptions.customFilterMessage = value;

          // Update control
          if (mTxtSearch) {
            mTxtSearch.BlankTip(mOptions.customFilterMessage);
          }
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "Grid",

      ClearColumns: ClearColumns,
      GetColumnByIndex: GetColumnByIndex,
      GetColumnByKey: GetColumnByKey,

      AddColumnBoolean: AddColumnBoolean,
      AddColumnColourBlock: AddColumnColourBlock,
      AddColumnColourFlag: AddColumnColourFlag,
      AddColumnCurrency: AddColumnCurrency,
      AddColumnDate: AddColumnDate,
      AddColumnDateTime: AddColumnDateTime,
      AddColumnDrilldown: AddColumnDrilldown,
      AddColumnDouble: AddColumnDouble,
      AddColumnHtml: AddColumnHtml,
      AddColumnIcon: AddColumnIcon,
      AddColumnInteger: AddColumnInteger,
      AddColumnString: AddColumnString,
      AddColumnCode: AddColumnCode,

      AddColumnFromTaskManager2UserDataHeading: AddColumnFromTaskManager2UserDataHeading,

      AllowAddRows: AllowAddRows,

      ColumnCount: ColumnCount,

      SortColumnsByArray: SortColumnsByArray,

      MergeColumnHeaders: MergeColumnHeaders,

      ActivateFirstDataRow: ActivateFirstDataRow,
      ActivateLastDataRow: ActivateLastDataRow,

      ActiveDataRowIndex: ActiveDataRowIndex,         // Index in the grid
      ActiveDataRowListIndex: ActiveDataRowListIndex, // Index in the underlying virtual data collection

      AddRow: AddRow,

      GetSelectedRowDetailsFromUniqueProperty: GetSelectedRowDetailsFromUniqueProperty,
      SetSelectedRowDetailsFromUniqueProperty: SetSelectedRowDetailsFromUniqueProperty,
      GetSelectedRowIndexes: GetSelectedRowIndexes,
      SetSelectedRowIndexes: SetSelectedRowIndexes,
      SetSelectedRowIndexesForSortableGrid: SetSelectedRowIndexesForSortableGrid,
      SetSelectedVirtualDataRowIndexesForSortableGrid: SetSelectedVirtualDataRowIndexesForSortableGrid,
      SetRowSelectorIcon: SetRowSelectorIcon,
      SelectAllRows: SelectAllRows,
      GetVirtualDataForSelectedRows: GetVirtualDataForSelectedRows,

      GetColumnsList: GetColumnsList,

      SetColumnCollection: SetColumnCollection,
      SetColumnList: SetColumnList,
      SetColumnListCsv: SetColumnListCsv,

      GroupByColumnsUpdate: GroupByColumnsUpdate,

      ColumnCaption: ColumnCaption,
      ColumnVisible: ColumnVisible,

      Actions: Actions,

      RowMoveUp: RowMoveUp,
      RowMoveDown: RowMoveDown,

      CustomFilterMessage: CustomFilterMessage,
      Editing: function () { return mEditing; },
      Element: Element,
      ExportData: ExportData,
      ExportFileName: ExportFileName,
      Focus: Focus,
      GetVirtualClass: GetVirtualClass,
      GroupByColumns: GroupByColumns,
      PerformRowDrilldown: PerformRowDrilldown,
      ReadOnly: ReadOnly,
      Refresh: Refresh,
      RefreshButtons: RefreshButtons,
      RefreshRow: RefreshRow,
      RemoveRowAndCollectionItem: RemoveRowAndCollectionItem,
      RemoveSelectedRowsAndCollectionItems: RemoveSelectedRowsAndCollectionItems,
      ResizeFromParent: ResizeFromParent,
      SearchClear: SearchClear,
      SelectedColumn: SelectedColumn,
      SelectedColumnKey: SelectedColumnKey,
      Sort: Sort,
      Validate: Validate,
      VirtualDataRefresh: VirtualDataRefresh,
      Visible: Visible,

      // Friend
      GetColumnDataForPieChart: GetColumnDataForPieChart,
    };

    // Associate this control to HTML input element (for container validation)
    mWrapperElement.prop("is-control", _self);

    return _self;
  }



  // =========================================
  // PUBLIC: Document Manager Combo Box object
  // =========================================
  function DocumentManagerComboBox(e, options) {

    var mComboBox;
    var mFileUploadElement;
    var mFileUploadId;
    var mFileUploadInitialised = false;
    var mFileUploadSection;
    var mOptions;
    var mPreviewCache;
    var mPreviewElement;
    var mPreviewFileName = "";
    var mSourceType;
    var mSourceId;
    var mSuppliedOnChange = null;
    var mTextOriginal = "";
    var mRefreshOptions;
    var mWrapperElement;

    // Extend options with defaults
    var Defaults = {
      allowNew: true,
      fileTypes: "*",
      previewHeight: 80,
      showPreview: true,
    };
    mOptions = $.extend({}, Defaults, options);

    // Forced options/ defaults (some of these are just initialisation values that will be set later)
    mSuppliedOnChange = mOptions.onChange;
    mOptions.maxLength = 255;
    mOptions.limitToList = false; // Just in case!
    mOptions.width = "100%";
    mOptions.onChange = function (sender, e) {
      // Probably a dyanmically created control that hasn't had this method attached (J033386)
      if (!mFileUploadElement[0].GetFiles) {
        InputFileInitialise(mFileUploadElement);
      }

      // Update Layout
      UpdateLayout();

      // Notify
      if (mSuppliedOnChange) {
        mSuppliedOnChange(sender, e);
      }
      else {
        if (e) e.ChangeHandled = true;
      }
      mTextOriginal = mComboBox.Text();
    };

    // Create ComboBox
    mComboBox = widget.UI.ComboBox(e, mOptions);
    var cbe = mComboBox.WrapperElement();

    // Add wrapper and preview
    cbe.wrap("<div class='is-dm-combobox'></div>");
    mWrapperElement = $(cbe.parent());
    if (mOptions.showPreview) {
      mPreviewElement = $("<div class='preview' style='min-height:" + mOptions.previewHeight + "px;'><img style='height:" + mOptions.previewHeight + "px'/></div>");
      mWrapperElement.append(mPreviewElement);
    }

    // Create File Upload section
    if (mOptions.allowNew) {
      mFileUploadId = CreateGuid(true);
      mFileUploadSection = $("<div class='is-file-upload widget-control'><label for='" + mFileUploadId + "'></label></div>");
      mFileUploadElement = $("<input type='file' id='" + mFileUploadId + "'/>");
      switch (mOptions.fileTypes.toUpperCase()) {
        case "[IMAGES]":
          mFileUploadElement.attr("accept", "image/*");
          break;

        case "[VIDEOS]":
          mFileUploadElement.attr("accept", "video/mp4");
          break;

        case "[IMAGESVIDEOS]":
          mFileUploadElement.attr("accept", "image/*, video/mp4");
          break;
      }
      mFileUploadSection.append(mFileUploadElement);
      mFileUploadSection.insertBefore(cbe);
    }

    // Initialise
    mComboBox.Visible(true);
    if (mPreviewElement) mPreviewElement.hide();
    mFileUploadSection.hide();


    // ------------------
    // PRIVATE: Normalise
    // ------------------
    function Normalise() {
      if (mFileUploadInitialised) return;

      // Flag as normalised
      mFileUploadInitialised = true;

      // Handle change event
      // NOTE: Must be done here since form functionality will have substituted the original control in the InputFileInitialise method
      mFileUploadElement = $("#" + mFileUploadId);
      mFileUploadElement.change(function () {
        if (mFileUploadElement[0].GetFiles().length == 0) {
          // Revert back to ComboBox if cleared
          // NOTE: In some browsers, this will be called immediately since their file open dialog seems to be asynchronous. The change event that is called when a file is selected fixes this up
          mComboBox.Text("");
          UpdateLayout();
          mComboBox.Focus();

          // Notify
          if (mSuppliedOnChange) mSuppliedOnChange(_self, null);
        }
        else {
          // Ensure file list is showing (may have been hidden when locating the first file if file open dialog was asynchronous)
          mComboBox.Visible(false);
          mFileUploadSection.show();
          UpdateLayout();

          // Notify
          if (mSuppliedOnChange) mSuppliedOnChange(_self, null);
        }
      });
    }

    // ----------------------
    // PRIVATE: Update Layout
    // ----------------------
    function UpdateLayout() {
      // Normalise before doing anything else
      Normalise();

      // Initialise
      var s = mComboBox.Text();

      // New File?
      if (mOptions.allowNew && (s.toUpperCase() == "[NEW FILE...]" || IsNewFile())) {
        mComboBox.Visible(false);
        mFileUploadSection.show();

        // Add file now
        $("label.addfile", mFileUploadSection).trigger("click");
        var ti = window.setTimeout(function () {
          window.clearTimeout(ti);
          ti = null;

          if (mFileUploadElement[0].GetFiles().length == 0) {
            // Revert back to ComboBox if cleared
            mComboBox.Text("");
            UpdateLayout();
            mComboBox.Focus();
          }
        }, 100);
      }
      else {
        mComboBox.Visible(true);
        mFileUploadSection.hide();
      }

      // Preview
      if (mOptions.showPreview) UpdatePreview();
    }

    // -----------------------
    // PRIVATE: Update Preview
    // -----------------------
    function UpdatePreview() {
      // Changed?
      if (mComboBox.Text() == mPreviewFileName) return;

      // Refreshed?
      if (!mSourceType || !mSourceId) return;

      if (mPreviewElement) {
        var img = $("img", mPreviewElement);
        mPreviewFileName = mComboBox.Text();

        // Supports preview?
        var supportsPreview = mPreviewFileName && !IsNewFile() && mPreviewFileName.toUpperCase() != "[NEW FILE...]";
        if (supportsPreview) {
          var n = mPreviewFileName.lastIndexOf(".");
          if (n > 0) {
            var extension = mPreviewFileName.substr(n + 1).toUpperCase();
            switch (extension) {
              case "BMP":
              case "GIF":
              case "ICO":
              case "JPG":
              case "JPEG":
              case "PNG":
                break;

              default:
                supportsPreview = false;
            }
          }
        }

        if (supportsPreview) {
          img.attr("src", "");
          mPreviewElement.show();

          // Fetch Preview
          if (mPreviewCache[mPreviewFileName]) {
            // Use Cached Image
            img.attr("src", mPreviewCache[mPreviewFileName]);
          }
          else {
            // Fetch
            var params = { sourceType: mSourceType, sourceId: mSourceId, fileName: mPreviewFileName, previewHeight: mOptions.previewHeight };
            widget._SystemGetString("DocumentManagerComboBox_GetPreview", params,
              function (data) {
                if (mPreviewFileName != mComboBox.Text()) {
                  // Changed!
                }
                else {
                  // Update
                  img.attr("src", data);

                  // Cache
                  mPreviewCache[mPreviewFileName] = data;
                }
              },

              function (data) {
                widget.RegisterError("widget_ui.DocumentManagerComboBox: Failed to get preview details: " + data);
              });
          }
        }
        else {
          img.attr("src", "");
          mPreviewElement.hide();
          mPreviewFileName = "";
        }
      }

    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return mComboBox.Text();
      }
      else {
        // Set
        if (value != mTextOriginal) {
          mComboBox.Text(value);

          // Update Preview
          UpdatePreview();
        }

        mTextOriginal = value;
      }
    }

    // ---------------
    // PUBLIC: Refresh
    // ---------------
    function Refresh(sourceType, sourceId, options) {
      // Initialise
      mSourceType = sourceType;
      mSourceId = sourceId;
      mPreviewCache = {};

      // Extend options with defaults
      var RefreshDefaults = {
        fileTypes: "*",
      };
      mRefreshOptions = $.extend({}, RefreshDefaults, options);

      // Clear list
      mComboBox.ListFromCsvString("");

      // Fetch List
      var params = { sourceType: sourceType, sourceId: sourceId, fileTypes: mRefreshOptions.fileTypes };

      // Fetch
      if (sourceType) {
        widget._SystemGetString("DocumentManagerComboBox_GetList", params,
          function (data) {
            // Parse
            data = JSON.parse(data);

            // Update List
            if (mOptions.allowNew) {
              data.unshift("[New file...]");
            }
            mComboBox.ListFromArray(data);

            // Update Preview (Refresh may have been called after text was set)
            UpdatePreview();
          },

          function (data) {
            widget.RegisterError("widget_ui.DocumentManagerComboBox: Failed to refresh details: " + data);
          });
      }
    }

    // --------------------------------------------------
    // PUBLIC: Is the selected or new file an Image File?
    // --------------------------------------------------
    function IsImageFile() {
      var fileName = "";
      var extension = "";

      if (mFileUploadElement && mFileUploadElement.length != 0 && mFileUploadElement[0].GetFiles && mOptions.allowNew && mFileUploadElement[0].GetFiles().length != 0) {
        // New file
        fileName = mFileUploadElement[0].GetFileName();
      }
      else {
        // Existing file
        fileName = mComboBox.Text();
      }

      var n = fileName.lastIndexOf(".");
      if (n) {
        extension = fileName.substr(n + 1).toUpperCase();
      }
      switch (extension) {
        case "BMP":
        case "GIF":
        case "ICO":
        case "JPG":
        case "JPEG":
        case "PNG":
          return true;

        default:
          return false;
      }
    }

    // --------------------------------------------------
    // PUBLIC: Is the selected or new file an Video File?
    // --------------------------------------------------
    function IsVideoFile() {
      var fileName = "";
      var extension = "";

      if (mFileUploadElement && mFileUploadElement.length != 0 && mFileUploadElement[0].GetFiles && mOptions.allowNew && mFileUploadElement[0].GetFiles().length != 0) {
        // New file
        fileName = mFileUploadElement[0].GetFileName();
      }
      else {
        // Existing file
        fileName = mComboBox.Text();
      }

      var n = fileName.lastIndexOf(".");
      if (n) {
        extension = fileName.substr(n + 1).toUpperCase();
      }
      switch (extension) {
        case "MP4":
          return true;

        default:
          return false;
      }
    }

    // --------------------
    // PUBLIC: Is New File?
    // --------------------
    function IsNewFile() {
      // Normalise
      Normalise();

      if (mFileUploadElement && mFileUploadElement.length != 0 && mFileUploadElement[0].GetFiles) {
        return mOptions.allowNew && mFileUploadElement[0].GetFiles().length != 0;
      }
      else {
        return false;
      }
    }

    // -----------------------------------------
    // PUBLIC: Get File data required for upload
    // -----------------------------------------
    function GetFileData() {
      // Normalise before doing anything else
      Normalise();

      return mFileUploadElement[0];
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "DocumentManagerComboBox",

      GetFileData: GetFileData,
      IsNewFile: IsNewFile,
      IsImageFile: IsImageFile,
      IsVideoFile: IsVideoFile,
      Refresh: Refresh,

      /* From ComboBox */
      AllowBlank: mComboBox.AllowBlank,
      AutoReadOnly: mComboBox.AutoReadOnly,
      BlankTip: mComboBox.BlankTip,
      Buttons: mComboBox.Buttons,
      ButtonsDefine: mComboBox.ButtonsDefine,
      Caption: mComboBox.Caption,
      Element: mComboBox.Element,
      Focus: mComboBox.Focus,
      ReadOnly: mComboBox.ReadOnly,
      Text: Text,
      Visible: mComboBox.Visible,
      VisibleRow: mComboBox.VisibleRow,
      WidthResizeFromParent: mComboBox.WidthResizeFromParent,
    };

    return _self;
  }



  // =============================
  // PUBLIC: Icon Combo Box object
  // =============================
  function IconComboBox(e, options) {

    var mComboBox;
    var mIconElement;
    var mIconImage;
    var mOptions = options;
    var mTextOriginal = "";
    var mSuppliedOnChange = null;

    // Forced options/ defaults (some of these are just initialisation values that will be set later)
    if (!options.iconPrefix) options.iconPrefix = "";
    if (!options.iconSuffix) options.iconSuffix = "";
    mSuppliedOnChange = options.onChange;
    options.onChange = function (sender, e) {
      // Update Icon
      UpdateIcon();

      // Notify
      if (mSuppliedOnChange) {
        mSuppliedOnChange(sender, e);
      }
      else {
        if (e) e.ChangeHandled = true;
      }
      mTextOriginal = mComboBox.Text();
    };
    options.onFormatItem = function (sender, e) {
      // Format display value for list to include an icon
      if (e.displayValue) {
        e.displayValue = "<img style='width:16px; height:16px; overflow:hidden; display:inline-block; vertical-align:middle' src='" + widget.GetIconUrl(options.iconPrefix + e.displayValue + options.iconSuffix, 16) + "'/>&nbsp;" + e.displayValue;
      }
      else {
        e.displayValue = "<div style='border:1px solid rgba(0,0,0,0.1); width:16px; height:16px; overflow:hidden; display:inline-block; vertical-align:middle'></div>&nbsp;" + e.displayValue;
      }
    };

    // Create ComboBox (always use a ComboBox)
    mComboBox = widget.UI.ComboBox(e, options);
    var ce = mComboBox.Element();
    ce.css("padding-left", "22px");
    mComboBox.WrapperElement().addClass("is-icon-combobox");

    // Clear Combo Box - J029028
    mComboBox.Text("");

    // Create Icon Element
    mIconElement = $("<div style='width:16px; position:absolute; top:3px; left:3px; bottom:3px'><img style='width:16px; height:16px; display:none;'/></div>");
    mIconElement.insertBefore(ce);
    mIconImage = $("img", mIconElement);

    // Initialise


    // ---------------------
    // PRIVATE: Rebuild List
    // ---------------------
    function RebuildList() {
      // NOTE: options.listOther is for validation purposes only (not yet implemented)
      mComboBox.ListFromCsvString(options.list);
    }

    // --------------------
    // PRIVATE: Update Icon
    // --------------------
    function UpdateIcon() {
      var s = mComboBox.Text();
      if (s) {
        mIconImage.attr("src", widget.GetIconUrl(mOptions.iconPrefix + s + options.iconSuffix, 16));
        mIconImage.show();
      }
      else {
        mIconImage.hide();
      }
    }

    // ----------------------------------
    // PUBLIC: Set List from a CSV String
    // ----------------------------------
    function ListFromCsvString(value) {
      mOptions.list = value;
      RebuildList();
    }

    // ---------------------------------------
    // PUBLIC: Set ListOther from a CSV String
    // ---------------------------------------
    function ListOtherFromCsvString(value) {
      mOptions.listOther = value;
      RebuildList();
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return mComboBox.Text();
      }
      else {
        // Set
        if (value != mTextOriginal) {
          mComboBox.Text(value);

          // Update Icon
          UpdateIcon();
        }

        mTextOriginal = value;
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "IconComboBox",

      ListFromCsvString: ListFromCsvString,
      ListOtherFromCsvString: ListOtherFromCsvString,

      /* From ComboBox */
      AllowBlank: mComboBox.AllowBlank,
      AutoReadOnly: mComboBox.AutoReadOnly,
      BlankTip: mComboBox.BlankTip,
      Caption: mComboBox.Caption,
      Element: mComboBox.Element,
      Focus: mComboBox.Focus,
      ReadOnly: mComboBox.ReadOnly,
      Text: Text,
      Visible: mComboBox.Visible,
      VisibleRow: mComboBox.VisibleRow,
      WidthResizeFromParent: mComboBox.WidthResizeFromParent,
    };

    return _self;
  }



  // =======================================
  // PUBLIC: Colour Chooser Combo Box object
  // =======================================
  function ColourChooserComboBox(e, options) {

    var mComboBox;
    var mIconElement;
    var mIconImage;
    var mOptions = options;
    var mTextOriginal = "";
    var mSuppliedOnChange = null;

    // Forced options/ defaults (some of these are just initialisation values that will be set later)
    mSuppliedOnChange = options.onChange;
    if (!options.listCsv) options.listCsv = "Black,Blue,Green,Cyan,Gray,Red,Magenta,Yellow,White,AliceBlue,AntiqueWhite,Aqua,Aquamarine,Azure,Beige,Bisque,BlanchedAlmond,BlueViolet,Brown,BurlyWood,CadetBlue,Chartreuse,Chocolate,Coral,CornflowerBlue,Cornsilk,Crimson,DarkBlue,DarkCyan,DarkGoldenrod,DarkGray,DarkGreen,DarkKhaki,DarkMagenta,DarkOliveGreen,DarkOrange,DarkOrchid,DarkRed,DarkSalmon,DarkSeaGreen,DarkSlateBlue,DarkSlateGray,DarkTurquoise,DarkViolet,DeepPink,DeepSkyBlue,DimGray,DodgerBlue,Firebrick,FloralWhite,ForestGreen,Fuchsia,Gainsboro,GhostWhite,Gold,Goldenrod,GreenYellow,Honeydew,HotPink,IndianRed,Indigo,Ivory,Khaki,Lavender,LavenderBlush,LawnGreen,LemonChiffon,LightBlue,LightCoral,LightCyan,LightGoldenrodYellow,LightGray,LightGreen,LightPink,LightSalmon,LightSeaGreen,LightSkyBlue,LightSlateGray,LightSteelBlue,LightYellow,Lime,LimeGreen,Linen,Maroon,MediumAquamarine,MediumBlue,MediumOrchid,MediumPurple,MediumSeaGreen,MediumSlateBlue,MediumSpringGreen,MediumTurquoise,MediumVioletRed,MidnightBlue,MintCream,MistyRose,Moccasin,NavajoWhite,Navy,OldLace,Olive,OliveDrab,Orange,OrangeRed,Orchid,PaleGoldenrod,PaleGreen,PaleTurquoise,PaleVioletRed,PapayaWhip,PeachPuff,Peru,Pink,Plum,PowderBlue,Purple,RosyBrown,RoyalBlue,SaddleBrown,Salmon,SandyBrown,SeaGreen,SeaShell,Sienna,Silver,SkyBlue,SlateBlue,SlateGray,Snow,SpringGreen,SteelBlue,Tan,Teal,Thistle,Tomato,Turquoise,Violet,Wheat,WhiteSmoke,YellowGreen";
    options.onChange = function (sender, e) {
      // Update Icon
      UpdateIcon();

      // Notify
      if (mSuppliedOnChange) {
        mSuppliedOnChange(sender, e);
      }
      else {
        if (e) e.ChangeHandled = true;
      }
      mTextOriginal = mComboBox.Text();
    };
    options.onFormatItem = function (sender, e) {
      // Format display value for list to include a colour icon
      if (e.displayValue) {
        e.displayValue = "<div style='border:1px solid rgba(0,0,0,0.1); width:16px; height:16px; overflow:hidden; display:inline-block; vertical-align:middle; background-color:" + e.displayValue + "'>&nbsp;</div>&nbsp;" + e.displayValue;
      }
      else {
        e.displayValue = "<div style='border:1px solid rgba(0,0,0,0.1); width:16px; height:16px; overflow:hidden; display:inline-block; vertical-align:middle'></div>&nbsp;" + e.displayValue;
      }
    };

    // Create ComboBox (always use a ComboBox)
    mComboBox = widget.UI.ComboBox(e, options);
    var ce = mComboBox.Element();
    ce.css("padding-left", "22px");
    mComboBox.WrapperElement().addClass("is-icon-combobox");

    // Create Icon Element
    mIconElement = $("<div style='width:16px; position:absolute; top:3px; left:3px; bottom:3px'><div style='width:16px; height:16px; display:none;'></div></div>");
    mIconElement.insertBefore(ce);
    mIconImage = $("div", mIconElement);

    // Initialise


    // ---------------------
    // PRIVATE: Rebuild List
    // ---------------------
    function RebuildList() {
      // NOTE: options.listOther is for validation purposes only (not yet implemented)
      mComboBox.ListFromCsvString(options.list);
    }

    // --------------------
    // PRIVATE: Update Icon
    // --------------------
    function UpdateIcon() {
      var s = mComboBox.Text();
      if (s) {
        mIconImage.css("background-color", s);
        mIconImage.show();
      }
      else {
        mIconImage.hide();
      }
    }

    // ----------------------------------
    // PUBLIC: Set List from a CSV String
    // ----------------------------------
    function ListFromCsvString(value) {
      mOptions.list = value;
      RebuildList();
    }

    // ---------------------------------------
    // PUBLIC: Set ListOther from a CSV String
    // ---------------------------------------
    function ListOtherFromCsvString(value) {
      mOptions.listOther = value;
      RebuildList();
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return mComboBox.Text();
      }
      else {
        // Set
        if (value != mTextOriginal) {
          mComboBox.Text(value);

          // Update Icon
          UpdateIcon();
        }

        mTextOriginal = value;
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "ColourChooserComboBox",

      ListFromCsvString: ListFromCsvString,

      /* From ComboBox */
      AllowBlank: mComboBox.AllowBlank,
      AutoReadOnly: mComboBox.AutoReadOnly,
      BlankTip: mComboBox.BlankTip,
      Caption: mComboBox.Caption,
      Element: mComboBox.Element,
      Focus: mComboBox.Focus,
      ReadOnly: mComboBox.ReadOnly,
      Text: Text,
      Visible: mComboBox.Visible,
      VisibleRow: mComboBox.VisibleRow,
      WidthResizeFromParent: mComboBox.WidthResizeFromParent,
    };

    return _self;
  }



  // =======================================
  // PUBLIC: Permission Key Combo Box object
  // =======================================
  function PermissionKeyComboBox(e, options) {

    var mComboBox;
    var mIconElement;
    var mIconImage;
    var mOptions = options;
    var mTextOriginal = "";
    var mSuppliedOnChange = null;

    // Forced options/ defaults (some of these are just initialisation values that will be set later)
    mSuppliedOnChange = options.onChange;
    mOptions.maxLength = 50;
    if (mOptions.allowViewEffectivePermissions === undefined) mOptions.allowViewEffectivePermissions = true;

    options.onChange = function (sender, e) {
      // Update Icon
      UpdateIcon();

      // Notify
      if (mSuppliedOnChange) {
        mSuppliedOnChange(sender, e);
      }
      else {
        if (e) e.ChangeHandled = true;
      }
      mTextOriginal = mComboBox.Text();
    };
    options.onButtonClick = function (sender, e) {
      switch (e.id) {
        case "EffectivePermissions":
          // Effective Permissions Lookup
          var startupParametersJson = JSON.stringify({ permissionKey: mComboBox.Text(), readOnly: mComboBox.ReadOnly() });
          widget.UI.Forms.ShowHtmlWidgetModal("HtmlWidget:EffectivePermissionsViewer", { startupParametersJson: startupParametersJson }, function (actionId, data) {
          //widget.UI.Forms.ShowHtmlWidgetModal("PERMISSIONCHOOSER", { startupParametersJson: startupParametersJson }, function (actionId, data) {
            if (!mComboBox.ReadOnly()) {
              // Update Permission Key
              Text(data);
              var ti = window.setTimeout(function () {
                window.clearTimeout(ti);
                ti = null;

                mComboBox.Focus();
              }, 100);
            }
          });
          break;

        default:
          window.alert("Unhandled button '" + e.id + "'.");
      }
    };
    options.onFormatItem = function (sender, e) {
      // Format display value for list to include a colour icon
      if (e.displayValue) {
        var icon = "Lock";
        var overlay = "Check";
        if (e.displayValue.startsWith("UserDefined.")) {
          icon = "User";
        }
        else if (e.displayValue.startsWith("Cloud.")) {
          icon = "Internet";
        }
        var item = mPermissionKeyListCache[e.listIndex];
        if (item.b == 1) {
          overlay = "Cross";
        }
        e.displayValue = "<img style='width:16px; height:16px; overflow:hidden; display:inline-block; vertical-align:middle' src='" + widget.GetIconUrl(icon + "|" + overlay, 16) + "'/>&nbsp;" + e.displayValue;
      }
      else {
        e.displayValue = "<div style='border:1px solid rgba(0,0,0,0.1); width:16px; height:16px; overflow:hidden; display:inline-block; vertical-align:middle'></div>&nbsp;" + e.displayValue;
      }
    };

    // Create ComboBox (always use a ComboBox)
    mComboBox = widget.UI.ComboBox(e, options);
    var ce = mComboBox.Element();
    ce.css("padding-left", "22px");
    mComboBox.WrapperElement().addClass("is-icon-combobox");

    // Add button to show Effective Permissions Viewer
    if (mOptions.allowViewEffectivePermissions) {
      mComboBox.ButtonsDefine([{ id: "EffectivePermissions", tooltipText: "Show Effective Permissions for this Permission Key", icon: "Find" }]);
    }

    // Create Icon Element
    mIconElement = $("<div style='width:16px; position:absolute; top:3px; left:3px; bottom:3px'><img style='width:16px; height:16px; display:none;'/></div>");
    mIconElement.insertBefore(ce);
    mIconImage = $("img", mIconElement);

    // Initialise
    RebuildList();


    // ---------------------
    // PRIVATE: Rebuild List
    // ---------------------
    function RebuildList() {
      // Check global flag (in case multiple lists are trying to rebuild at once when they should share a global list)
      if (mPermissionKeyListFetching) {
        // Retry in a second
        var ti = window.setTimeout(function () {
          window.clearTimeout(ti);
          ti = null;

          RebuildList();
        }, 1000);
        return;
      }

      // Already fetched?
      if (mPermissionKeyListCache) {
        RebuildList_Done();
        return;
      }

      // Fetching
      mPermissionKeyListFetching = true;

      // Fetch
      widget._SystemGetString("PermissionKeys_GetList", {},
        function (data) {
          // Parse
          mPermissionKeyListCache = JSON.parse(data);

          // Unblock
          mPermissionKeyListFetching = false;

          // Done
          RebuildList_Done();

          // Update Icon (just in case)
          UpdateIcon();
        },

        function (data) {
          widget.RegisterError("widget_ui.PermissionKeyComboBox: Failed to retrieve list: " + data);

          // Unblock
          mPermissionKeyListFetching = false;
        });

    }

    function RebuildList_Done() {
      var arr = [];
      for (var i = 0; i < mPermissionKeyListCache.length; i++) {
        var item = mPermissionKeyListCache[i];
        arr.push(item.k);
      }

      mComboBox.ListFromArray(arr);
    }

    // --------------------
    // PRIVATE: Update Icon
    // --------------------
    function UpdateIcon() {
      var s = mComboBox.Text();
      if (s) {
        var icon = "Lock";
        var overlay = "Check";
        if (s.startsWith("UserDefined.")) {
          icon = "User";
        }
        else if (s.startsWith("Cloud.")) {
          icon = "Internet";
        }

        // Locate Permission
        var item;
        if (mPermissionKeyListCache) {
          for (var i = 0; i < mPermissionKeyListCache.length; i++) {
            if (mPermissionKeyListCache[i].k == s) {
              item = mPermissionKeyListCache[i];
              break;
            }
          }
        }

        if (!item) {
          icon = "Error";
          overlay = "";
        }
        else if (item.b == 1) {
          overlay = "Cross";
        }

        mIconImage.attr("src", widget.GetIconUrl(icon + "|" + overlay, 16));
        mIconImage.show();
      }
      else {
        mIconImage.hide();
      }
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return mComboBox.Text();
      }
      else {
        // Set
        if (value != mTextOriginal) {
          mComboBox.Text(value);

          // Update Icon
          UpdateIcon();
        }

        mTextOriginal = value;
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "PermissionKeyComboBox",

      /* From ComboBox */
      AllowBlank: mComboBox.AllowBlank,
      AutoReadOnly: mComboBox.AutoReadOnly,
      BlankTip: mComboBox.BlankTip,
      Caption: mComboBox.Caption,
      Element: mComboBox.Element,
      Focus: mComboBox.Focus,
      ListIndex: mComboBox.ListIndex,
      ReadOnly: mComboBox.ReadOnly,
      Text: Text,
      Visible: mComboBox.Visible,
      VisibleRow: mComboBox.VisibleRow,
      WidthResizeFromParent: mComboBox.WidthResizeFromParent,
    };

    return _self;
  }



  // =========================================
  // PUBLIC: Information List Combo Box object
  // =========================================
  function InformationListComboBox(e, options) {

    // Use finPOWER Connect Cloud InformationListComboBox (to respect picker panel etc)
    if (!mDisableProxyControls && !mDisableControlStyling && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      if (typeof e == "string") {
        e = $("#" + e);
      }
      e.attr("is-created", "y");
      options.widgetDocument = window.document;
      var c = window.parent.$UI.InformationListComboBox(e, options);
      return c;
    }

    var mComboBox;
    var mInformationList = null;
    var mOptions = options;
    var mOpenAdminFormElement;
    var mOverrideMaxLength = false;

    // Forced options/ defaults (some of these are just initialisation values that will be set later)
    options.showColumnHeadings = false;
    options.showDescription = false;
    if (!options.maxLength) options.maxLength = 50;
    if (!options.blankList) options.blankList = "";

    // Create ComboBox (always use a DBCombo since Information Lists can be straight lists or Alt/ Value lists)
    mComboBox = widget.UI.DBCombo(e, options);

    // ---------------------------
    // PUBLIC: Blank List property
    // ---------------------------
    function BlankList(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankList;
      }
      else {
        // Set
        if (value != mOptions.blankList) {
          // Update Blank List
          mOptions.blankList = value;
        }
      }
    }

    // ------------------------------------
    // PUBLIC: Override Max Length property
    // ------------------------------------
    function OverrideMaxLength(value) {
      if (value === undefined) {
        // Get
        return mOverrideMaxLength;
      }
      else {
        // Set
        if (value != undefined) {
          mOverrideMaxLength = value;
        }
      }
    }

    // ------------------------------------
    // PUBLIC: Set up this Information List
    // ------------------------------------
    function SetComboFromInformationList(informationListId, allowMandatoryOverride, callback, setDefaultValue) {
      // Initialise
      if (allowMandatoryOverride === undefined) allowMandatoryOverride = true;

      // Get Information List
      if (informationListId) {
        // Indicate that data is being fetched
        mComboBox.SetFetchingData(true);
        mComboBox.ShowDescription(false);
        if (!mOptions.width) mComboBox.WidthResizeFromParent();

        // Cached?
        if (mInformationListCache[informationListId]) {
          SetComboFromInformationList_Done(mInformationListCache[informationListId], informationListId, allowMandatoryOverride, callback, setDefaultValue);
          return;
        }

        // Get Information List
        widget._SystemGetString("GetInformationList", { id: informationListId },
          function (data) {
            SetComboFromInformationList_Done(data, informationListId, allowMandatoryOverride, callback, setDefaultValue);
          },

          function (data) {
            widget.RegisterError("widget_ui.InformationListComboBox: Failed to retrieve Information List: " + data);

            // Failed to get list. Not much we can do!
            if (callback) callback();
          });
      }
      else {
        // No Information List
        mComboBox.LimitToList(false);
        mComboBox.ListFromCsvString(mOptions.blankList);
        mComboBox.ShowDescription(false);
        if (!mOptions.width) mComboBox.WidthResizeFromParent();
      }
    }

    function SetComboFromInformationList_Done(dataRaw, informationListId, allowMandatoryOverride, callback, setDefaultValue) {
      if (dataRaw) {
        // Parse
        var data = JSON.parse(dataRaw);

        // Add 'Open Admin Form' button?
        if (data.CanViewAdminForm && !mOpenAdminFormElement && !mOptions.hideAdminFormButton) {
          mOpenAdminFormElement = $("<div class='is-button-strip' style='margin:0 !important'><ul><li title='Show Information List'><a><img src='" + widget.GetIconUrl("Form_Open") + "'/></a></li></ul></div>");
          mOpenAdminFormElement.insertAfter(mComboBox.ButtonElement());
          mOpenAdminFormElement.click(function () {
            widget.ExecuteApplicationShortcutUrl("app://formshow?form=InformationLists&id=" + encodeURIComponent(informationListId));
          });
        }

        // Bind to list
        if (data.ValuesAlt) {
          // Value + Alt Value
          var col = [];
          for (var i = 0; i < data.Values.length; i++) {
            col.push({ Value: data.Values[i], Description: data.ValuesAlt[i] });
          }
          mComboBox.RefreshFromCollection(col, "Value", "Description", "Value,Description");

          // Other properties
          mComboBox.ShowDescription(true);
        }
        else {
          // Value only
          var col = [];
          for (var i = 0; i < data.Values.length; i++) {
            col.push({ Value: data.Values[i] });
          }
          mComboBox.RefreshFromCollection(col, "Value", "", "Value");

          // Empty so use blankList property?
          if (col.length == 0 && mOptions.blankList) {
            mComboBox.ListFromCsvString(mOptions.blankList);
          }

          // Other properties
          mComboBox.ShowDescription(false);
        }

        // Store (required for sectioned lists)
        mInformationList = data;

        // Other properties
        if (allowMandatoryOverride) mComboBox.AllowBlank(!mInformationList.Mandatory);
        mComboBox.LimitToList(mInformationList.LimitToList);        
        if (!mOverrideMaxLength) mComboBox.MaxLength(mInformationList.MaxLength);

        // Resize
        mComboBox.WidthResizeFromParent(true);

        // Set default value
        if (setDefaultValue && !mComboBox.Text() && mInformationList.DefaultValue) {
          mComboBox.Text(mInformationList.DefaultValue);
        }
      }

      // Callback
      if (callback) callback();

      // Finalise
      mComboBox.SetFetchingData(false);
      mComboBox.WidthResizeFromParent(false);

      // Cache
      mInformationListCache[informationListId] = dataRaw;
    }

    // -------------------------------------------------------------
    // PUBLIC: Set up this control from a sectioned Information List
    // -------------------------------------------------------------
    function SetComboFromSectionedInformationList(informationListId, filters, callback) {
      // Build filter string
      var filter = "";
      if (filters) {
        for (var i = 0; i < filters.length; i++) {
          filter += filters[i] + "|";
        }
        filter = filter.toUpperCase();
      }

      // Initialise
      SetComboFromInformationList(informationListId, false, function () {
        // Get List
        var col = [];
        for (var i = 0; i < mInformationList.Values.length; i++) {
          var item = mInformationList.Values[i];
          if (filter) {
            // Apply filter
            var s = item.toUpperCase();
            if (s.substr(0, filter.length) == filter) {
              item = item.substr(filter.length);
              var n = item.indexOf("|");
              if (n != -1) item = item.substr(0, n);
            }
            else {
              item = null;
            }
          }
          else {
            // No filter so assume first section
            var n = item.indexOf("|");
            if (n != -1) item = item.substr(0, n);
          }

          // Add to list (if not already in list)
          if (item) {
            var found = false;
            for (var j = 0; j < col.length; j++) {
              if (item.toUpperCase() == col[j].Value.toUpperCase()) {
                found = true;
                break;
              }
            }
            if (!found) col.push({ Value: item });
          }
        }
        mComboBox.RefreshFromCollection(col, "Value", "", "Value");

        // Callback
        if (callback) callback();
      }, false);

    }

    // ------------------------------------------------------
    // PUBLIC: Set up this Information List for a Log Outcome
    // ------------------------------------------------------
    function SetLogOutcomeComboFromSectionedInformationList(informationListId, subject, alwaysIncludeOutcome, logSource) {

      var List = [];
      var ListAny = [];

      SetComboFromInformationList(informationListId, true, function () {
        if (mInformationList) {
          // Find items to include
          for (var i = 0; i < mInformationList.Values.length; i++) {
            var s = mInformationList.Values[i];
            var n = s.indexOf("|");
            if (n == -1) {
              ListAny.push(s);
            }
            else {
              var s2 = s.substr(0, n);
              if (s2.toUpperCase() == subject.toUpperCase()) {
                List.push(s.substr(n + 1));
              }
            }
          }

          // Sort
          // TODO:

          // Use 'Any' List if List contains no items
          if (List.length == 0) List = ListAny;

          // Always Include Item (add after sorted so it appears at the end)
          if (alwaysIncludeOutcome) {
            Runtime_StringArrayAddUnique(List, alwaysIncludeOutcome);
          }

          // Additional items (based on Log Source)
          switch (logSource) {
            case 510: // isefinLogSource.BankAccountEnquiryCreate
            case 500: // isefinLogSource.CreditEnquiry
              // TODO: Not if already in list
              list.push("Completed");
              list.push("Deleted");
              break;
          }

          // Set List
          var col = [];
          for (var i = 0; i < List.length; i++) {
            col.push({ Value: List[i] });
          }
          mComboBox.RefreshFromCollection(col, "Value", "", "Value");
        }
        else {
          // Something's gone wrong!
        }
      });
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "InformationListComboBox",

      BlankList: BlankList,      
      OverrideMaxLength: OverrideMaxLength,

      SetComboFromInformationList: SetComboFromInformationList,
      SetComboFromSectionedInformationList: SetComboFromSectionedInformationList,
      SetLogOutcomeComboFromSectionedInformationList: SetLogOutcomeComboFromSectionedInformationList,

      /* From DBCombo */
      AllowBlank: mComboBox.AllowBlank,
      AutoReadOnly: mComboBox.AutoReadOnly,
      BlankTip: mComboBox.BlankTip,
      Caption: mComboBox.Caption,
      Focus: mComboBox.Focus,
      MaxLength: mComboBox.MaxLength,
      ReadOnly: mComboBox.ReadOnly,
      Text: mComboBox.Text,
      Visible: mComboBox.Visible,
      VisibleRow: mComboBox.VisibleRow,
      WidthResizeFromParent: mComboBox.WidthResizeFromParent,
    };
    
    return _self;
  }



  // ========================
  // PUBLIC: NumberBox object
  // ========================
  function NumberBox(e, options) {

    var mButtonStrip;
    var mElement;
    var mElementRow;
    var mHasFocus = false;
    var mIsNumberField = false; // Is this a true HTML 5 number type field?
    var mIsValid = true;
    var mLabelElement;
    var mOptions;
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;
    var mValue = 0;
    var mValueIsBlank = true;
    var mValueOriginal = 0;
    var mValueOriginalIsBlank = true;
    var mWrapperElement;

    // Extend options with defaults
    NumberBoxDefaults = {
      blankTip: "",
      captionElement: "auto",
      cssClass: "is-numberbox",

      allowBlank: true,
      blankIfZero: false,
      fontBold: false,
      showSeparators: true,
      indentLevel: 0,

      decimals: -1,  // Currency
      percentage: false, // Display a percent symbol?

      maxValue: null,
      minValue: null,
      validationMessageBelow: false, // Set to true on the Account Financial details

      readOnly: false,
      autoReadOnly: true,

      visible: true,
      width: "auto",  // Other special values: "date"

      onButtonClick: null,
      onChange: null
    };
    mOptions = $.extend({}, NumberBoxDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.NumberBox: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Wrap element
    if (!mDisableControlStyling) {
      mElement.wrap("<span style='white-space:normal; display:inline-flex; align-items:center; padding:0; margin:0;' controltype='numberbox'/>");
    }
    mWrapperElement = $(mElement.parent());

    // Validation elements
    mValidationElement = $("<label style='display:none' class='is-validation-tip'></label>");
    mWrapperElement.append(mValidationElement);
    if (mOptions.validationMessageBelow) mValidationElement.addClass("below");

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Turn auto-complete and spellcheck off since it interferes with our functionality
    mElement.attr("autocomplete", "off");
    mElement.attr("spellcheck", "false");

    // Initialise
    UpdateElement();

    // Calculate width if 'auto'
    if (mOptions.width == "auto") {
      WidthResizeFromParent();
    }

    // Handle events to format/ unformat values and fire OnChange event
    if (mIsNumberField) {
      // HTML 5 number fields do not currently have a way to adjust decimals so do manually
      //mElement.blur(function () {
      //  // Initialise
      //  mHasFocus = false;

      //  // Format
      //  UpdateText();
      //});
      mElement.focus(function () {
        // Initialise
        mHasFocus = true;

        // Unformat for editing
        // Not allowed for HTML 5 Number type fields
      });
    }
    else {
      mElement.focus(function () {
        // Initialise
        mHasFocus = true;

        // Unformat for editing
        if (!mOptions.readOnly) UpdateText();

        // Select Text
        mElement.select();
      });
    }
    mElement.blur(function () {
      mHasFocus = false;

      if (!mOptions.readOnly) {
        TextToValue(mElement.val());
        if (Changed()) {
          NotifyChange();
        }
        mValueOriginal = Value();
        mValueOriginalIsBlank = ValueIsBlank();

        // Format
        UpdateText();
      }
    });

    // Enter key moves to next field (finPOWER Connect desktop only)?
    if (widget.Options.enterMovesToNextField) {
      mElement.on("keyup", function (e) {
        if (e.keyCode == 13) TriggerTab($(this));
      });
    }



    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // Width
      switch (mOptions.width.toUpperCase()) {
        case "AUTO":
          // Automatic width
          var max = 9999999999;
          var min = -9999999999;
          if (mOptions.maxValue != null) max = mOptions.maxValue;
          if (mOptions.minValue != null) min = mOptions.minValue;
          max = Runtime_FormatNumber(max, mOptions.decimals, false, false);
          min = Runtime_FormatNumber(min, mOptions.decimals, false, false);
          var chars = max.length;
          if (min.length > chars) chars = min.length;
          if (chars < 2) chars = 2;
          if (mOptions.percentage) chars += 1;
          mElement.removeClass("date");
          mElement.css("max-width", (chars * 0.8) + "em");
          mElement.css("width", "100%");
          break;

        case "DATE":
          // Size a per date control
          mElement.addClass("date");
          mElement.css("width", "");
          break;

        default:
          // Custom width
          mElement.removeClass("date");
          //if (mOptions.width) mElement.css({ width: mOptions.width });
          if (mOptions.width) {
            mElement.css({ "max-width": mOptions.width, width: "100%" });
          }
      }

      // Indent Level
      if (mLabelElement) {
        if (mOptions.indentLevel) {
          mLabelElement.addClass("is-indent-" + mOptions.indentLevel);
        }
        else {
          mLabelElement.removeClass("is-indent-1");
          mLabelElement.removeClass("is-indent-2");
        }
      }

      // Allow Blank
      if (mOptions.allowBlank) {
        mElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }

      if (mDisableControlStyling) {
        // Setting blank tip to blank affects: Material Design Lite
        if (mOptions.blankTip) mElement.attr("placeholder", mOptions.blankTip);
      }
      else {
        mElement.attr("placeholder", mOptions.blankTip);
      }

      // Font-Bold
      if (mOptions.fontBold) {
        if (mLabelElement) mLabelElement.css("font-weight", "bold");
        mElement.css("font-weight", "bold");
      }
      else {
        if (mLabelElement) mLabelElement.css("font-weight", "");
        mElement.css("font-weight", "");
      }

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("readonly");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Other
      mElement.attr("maxLength", mOptions.maxLength == 0 ? "" : mOptions.maxLength);
      mElement.attr("spellcheck", "false");

      // Validation message
      if (mIsValid) {
        mValidationElement.css({ display: "none" });
        mElement.removeClass("is-invalid");
      }
      else {
        mElement.addClass("is-invalid");
        if (mValidationText) {
          if (mValidationTextIsHtml) {
            mValidationElement.html(mValidationText);
          }
          else {
            mValidationElement.text(mValidationText);
          }
          mValidationElement.css({ display: "flex" });
        }
        else {
          mValidationElement.css({ display: "none" });
        }
      }

      // Number field specific
      if (mIsNumberField) {

      }

      // Tooltip
      var tooltip = "";
      if (mOptions.maxValue != null || mOptions.minValue != null) {
        tooltip = GetValidRangeText();
        if (tooltip) tooltip = "Valid range " + tooltip;
      }
      mElement.attr("title", tooltip);

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }
    }

    // ---------------
    // Update the Text
    // ---------------
    function TextToValue(text) {
      // Update value from text
      if (!mOptions.readOnly) {
        // Evaluate expression
        if (text && text.startsWith("=")) {
          // Safeguard
          var valid = "0123456789=,.()+*/\^% ";
          var invalid = false;
          for (var j = 0; j < text.length; j++) {
            var c = text.substr(j, 1);
            if (valid.indexOf(c) == -1) {
              invalid = true;
              break;
            }
          }

          if (invalid) {
            text = "";
            console.warn("Expression entered into NumberBox was ignored since it contains unrecognised information.");
          }
          else {
            text = "" + eval(text.substr(1));
          }
        }

        if (text == "") {
          mValueIsBlank = true;
          mValue = 0;
        }
        else {
          // Convert value
          mValueIsBlank = false;
          mValue = Runtime_ParseNumber(text, mOptions.decimals);
        }
      }

      // Update text
      UpdateText();
    }

    // ---------------
    // Update the Text
    // ---------------
    function UpdateText() {
      if (mValueIsBlank) {
        if (mHasFocus && !mOptions.readOnly) {
          // Entering value so display blank
          mElement.val("");
        }
        else {
          // Could allow a custom value for blank text but will just set to blank for now
          //TODO: Review
          mElement.val("");
        }
      }
      else {
        if (mHasFocus && !mOptions.readOnly) {
          // Entering value DON'T display blank
          if (mValue == 0) {
            // Don't format zero to show decimal places
            mElement.val("0");
          }
          else {
            if (mIsNumberField) {
              // Do nothing for HTML 5 number type fields
              //mElement.val(mValue)
            }
            else {
              // Unformat for data entry
              var decimals = mOptions.decimals;
              if (decimals == -1) decimals = widget.CurrencyDecimals(); // Ensure negatives are not bracketed for data-entry
              mElement.val(Runtime_FormatNumber(mValue, decimals, false, false));
            }
          }
        }
        else {
          // Format for display
          if (mOptions.blankIfZero && mValue == 0) {
            mElement.val("");
          }
          else {
            if (mIsNumberField) {
              // Do nothing for HTML 5 number type fields
            }
            else {
              var s = Runtime_FormatNumber(mValue, mOptions.decimals, mOptions.showSeparators, mOptions.blankIfZero);
              if (mOptions.percentage) s += "%";

              // Massive number that is formatted in a way that will mess up serialisation?
              var jsNumber = "" + mValue;
              if (jsNumber && (jsNumber.indexOf("e") != -1 || jsNumber.length >= 16)) {
                s = "";
                mValue = 0;
                mValueIsBlank = true;
                console.warn("Attempted to set NumberBox value to '" + jsNumber + "' which is likely to cause serialisation or parsing issues.");
              }

              mElement.val(s);
            }
          }
        }
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // -------------------------
    // PUBLIC: BlankTip property
    // -------------------------
    function BlankTip(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankTip;
      }
      else {
        // Set
        mOptions.blankTip = value;

        // Update element
        UpdateElement();
      }
    }

    // ----------------------------
    // PUBLIC: BlankIfZero property
    // ----------------------------
    function BlankIfZero(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankIfZero;
      }
      else {
        // Set
        mOptions.blankIfZero = value;

        // Update text
        UpdateText();
      }
    }

    // ---------------
    // PU8LIC: Buttons
    // ---------------
    function Buttons() {
      if (!mButtonStrip) {
        // Buttons
        var ebl = $("<div></div>");
        mWrapperElement.append(ebl);
        mButtonStrip = ButtonStrip(ebl, {
          onButtonClick: mOptions.onButtonClick,
          visible: false,
          parentControl: _self,
        });
      }

      return mButtonStrip;
    }

    // ----------------------
    // PUBLIC: Define Buttons
    // ----------------------
    function ButtonsDefine(buttons) {
      // Get Button Strip (created on-demand)
      var bs = Buttons();

      // Define
      if (!buttons) buttons = [];
      bs.ButtonsDefine(buttons);

      // Show
      mButtonStrip.Visible(buttons.length != 0);
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return !(mValue == mValueOriginal && mValueIsBlank == mValueOriginalIsBlank);
    }

    // -------------------------
    // PUBLIC: Decimals property
    // -------------------------
    function Decimals(value) {
      if (value === undefined) {
        // Get
        return mOptions.decimals;
      }
      else {
        // Set
        mOptions.decimals = value;

        // Update text
        UpdateText();
      }
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      // Notify
      var e = { ChangeHandled: false, ValueOriginal: mValueOriginal };
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset TextOriginal?
      if (e.ChangeHandled) mTextOriginal = mElement.val();

      // Update or clear validation message
      if (!mIsValid) Validate();
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // --------------------------
    // PUBLIC: Font Bold property
    // --------------------------
    function FontBold(value) {
      if (value === undefined) {
        // Get
        return mOptions.fontBold;
      }
      else {
        // Set
        if (value != mOptions.fontBold) {
          mOptions.fontBold = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------------
    // PUBLIC: Read-Only property
    // ----------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        if (mHasFocus) {
          // Commit value to prevent dirty reads, e.g., in grid editing
          TextToValue(mElement.val());
        }

        return mValue;
      }
      else {
        // Set
        if (value === null) {
          if (mOptions.allowBlank) {
            mValue = 0;
            mValueIsBlank = true;
          }
          else {
            mValue = 0;
          }
        }
        else {
          mValueIsBlank = false;

          // Round
          if (mOptions.decimals == -1) {
            value = widget.Round(value, widget.CurrencyDecimals());
          }
          else {
            value = widget.Round(value, mOptions.decimals);
          }

          mValue = value;
        }
        mValueOriginal = mValue;
        mValueOriginalIsBlank = mValueIsBlank;

        // Update text
        UpdateText();
      }
    }

    // -----------------------------
    // PUBLIC: ValueIsBlank property
    // -----------------------------
    function ValueIsBlank(value) {
      if (value === undefined) {
        // Get
        return mValueIsBlank;
      }
      else {
        // Set
        if (value) {
          mValueIsBlank = true;
          mValue = 0;
        }
        else {
          mValueIsBlank = false;
        }

        // Update text
        UpdateText();
      }
    }

    // -------------------------
    // PUBLIC: MaxValue property
    // -------------------------
    function MaxValue(value) {
      if (value === undefined) {
        return mOptions.maxValue;
      }
      else {
        // Set
        mOptions.maxValue = value;

        // Update
        UpdateElement();
      }
    }

    // -------------------------
    // PUBLIC: MinValue property
    // -------------------------
    function MinValue(value) {
      if (value === undefined) {
        return mOptions.minValue;
      }
      else {
        // Set
        mOptions.minValue = value;

        // Update
        UpdateElement();
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      // Auto-sizing is done in UpdateElement
      if (!fullWidth && mOptions.width.toUpperCase() == "AUTO") return;

      mWrapperElement.hide();
      var parentWidth = mWrapperElement.parent().innerWidth();
      mWrapperElement.show();
      var width = mOptions.width;
      var maxWidth = "";

      if (fullWidth) {
        width = "100%";
      }
      else {
        //TODO:
        if (mOptions.maxValue != null && mOptions.minValue != null) {
          //width = ("" + mOptions.maxValue).length;
          //mOptions.width = Math.min(width * 1.5, parentWidth) + "em";
          width = "6em";
        }
        else {
          width = "6em";
        }
        maxWidth = parentWidth + "px";
      }
      mWrapperElement.css({ width: width, maxWidth: maxWidth });
      mElement.css({ width: width, maxWidth: maxWidth });
    }

    // ------------------------
    // PUBLIC: Is control valid
    // ------------------------
    function IsValid() {
      return mIsValid ? true : false;
    }

    // ----------------------------------------------
    // PUBLIC: Validate (based on min and max values)
    // ----------------------------------------------
    function Validate() {
      // Initialise
      var valid = true;

      // Ensure value entered
      if ((!mOptions.allowBlank && ValueIsBlank()) ||
          (!mOptions.allowBlank && mOptions.blankIfZero && Value() == 0)) {
        // Clear validation message since it only applies to max and min values
        ValidationSet(true, "", false);

        return false;
      }

      // Validate?
      if (ValueIsBlank()) {
        // This is allowed - don't validate blank values
      }
      else if (mOptions.minValue != null || mOptions.maxValue != null) {
        var value = Value();

        if (mOptions.blankIfZero && mOptions.allowBlank && value == 0) {
          // This is allowed
        }
        else {
          if (valid && mOptions.minValue != null && value < mOptions.minValue) valid = false;
          if (valid && mOptions.maxValue != null && value > mOptions.maxValue) valid = false;
        }  
      }
      else {
        // Nothing to validate
      }

      // Update element
      if (valid) {
        ValidationSet(true, "", false);
      }
      else {
        ValidationSet(false, "Valid range " + GetValidRangeText(), false);
      }

      return valid;
    }

    // -------------------------------------------------------------------------
    // PRIVATE: Get text detailing the valid range (for validation and tooltips)
    // -------------------------------------------------------------------------
    function GetValidRangeText() {
      var s = "";

      if (mOptions.minValue != null) {
        if (mOptions.minValue == 0) {
          s += "0";
        }
        else {
          s += Runtime_FormatNumber(mOptions.minValue, mOptions.decimals, mOptions.showSeparators, false);
        }
      }
      if (mOptions.maxValue != null) {
        if (s) s += " ";
        s += "to " + Runtime_FormatNumber(mOptions.maxValue, mOptions.decimals, mOptions.showSeparators, false);
      }
      else if (s) {
        // Make valid ranges with a minimum but no maximum value unambiguous
        s += " or above";
      }

      return s;
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      mIsValid = isValid;
      if (validationText === undefined) mValidationText = ""; else mValidationText = validationText;
      if (validationTextIsHtml === undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

      // Update element
      UpdateElement();
    }

    // --------------------------------
    // PUBLIC: Set the OnChange handler
    // --------------------------------
    function OnChange(handler) {
      mOptions.onChange = handler;
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.TextBox.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "NumberBox",

      AllowBlank: AllowBlank,
      AutoReadOnly: AutoReadOnly,
      BlankTip: BlankTip,
      BlankIfZero: BlankIfZero,
      Buttons: Buttons,
      ButtonsDefine: ButtonsDefine,
      Caption: Caption,
      Changed: Changed,
      Decimals: Decimals,
      Element: Element,
      Focus: Focus,
      FontBold: FontBold,
      MaxValue: MaxValue,
      MinValue: MinValue,
      ReadOnly: ReadOnly,
      Value: Value,
      ValueIsBlank: ValueIsBlank,
      Visible: Visible,
      VisibleRow: VisibleRow,
      WidthResizeFromParent: WidthResizeFromParent,

      IsValid: IsValid,
      Validate: Validate,
      ValidationSet: ValidationSet,

      OnChange: OnChange,
    };

    // Associate this control to HTML input element (for container validation)
    mElement.prop("is-control", _self);

    return _self;
  }



  // ==============================
  // PUBLIC: Parameters Host object
  // ==============================
  function ParametersHost(e, options) {

    var mOptions = options;

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.ParametersHost: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Not available
    mElement.html("<div style='margin:4px; padding:4px; border:1px solid rgba(0,0,0,0.1); background-color:#ffffee; color:darkred; font-size:13px;'>Entry of parameters is only supported in finPOWER Connect Cloud.</div>");



    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "ParametersHost",

      Focus: function () { },
      Initialise: function () { },
      Refresh: function () { },
      ResizeFromParent: function () { },
      RestoreParametersFromSnapshot: function () { },
      Visible: function () { },

      GetParameterValues: function () { return ""; },
      UpdateParameterValues: function () { },
    };

    return _self;
  }



  // ===========================
  // PUBLIC: Preview Pane object
  // ===========================
  function PreviewPane(e, options) {

    var mButtonsElement;
    var mCache = {};
    var mContainerElement;
    var mContentElement;
    var mContentHtmlFull = "";
    var mContentIframe;
    var mErrorElement;
    var mElement;
    var mElementRow;
    var mLoaded = false;
    var mLoading = false;
    var mOptions;
    var mPopupCaptionElement;

    // Extend options with defaults
    PreviewPaneDefaults = {
      handleApplicationShortcuts: true,
      formActionHandler: null,
      applicationShortcutHandler: null,

      resizeToFit: false, // Resize to fit content once loaded
      resizeToFitAdditionalHeight: 0,

      showPrint: false,

      smartBackgroundColour: true,

      collapsedCaption: "Preview row",
      border: true,

      noCache: false, // Set to true when you do not want summary page caching to occur
    };
    mOptions = $.extend({}, PreviewPaneDefaults, options);

    // Get Element and validate (may be element or id)
    // NOTE: The parent element is likely to be a div element
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.PreviewPane: Parent element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Add popup caption (will be displayed via CSS if panel is collapsed, e.g., on a small screen)
    mPopupCaptionElement = $("<div class='collapsed-caption is-no-select' available='false'></div>");
    mPopupCaptionElement.html("<a>" + HtmlEncode(mOptions.collapsedCaption) + "</a>");
    mElement.append(mPopupCaptionElement);
    $("a", mPopupCaptionElement).click(function () { ShowPreviewInPopup(); });

    // Add iframe for content
    mContentIframe = $("<iframe/>");
    mElement.append(mContentIframe);

    // iOS will not constrain iframe size unless you turn scrolling off!
    if (Runtime_IsPlatformIOS) {
      mContentIframe.attr("scrolling", "no");
    }

    // Initialise
    UpdateElement();


    // ---------------------------
    // PRIVATE: Update the Element
    // ---------------------------
    function UpdateElement() {
      // CSS
      mElement.addClass("is-preview-pane");
      if (!mOptions.border) {
        mElement.css("border", "none");
      }

      // Loading
      mPopupCaptionElement.attr("available", !mLoading);
      if (mLoading) {
        mElement.addClass("is-loading");
      }
      else {
        mElement.removeClass("is-loading");
      }

      // Create buttons element (for button strip below preview pane)
      if (mOptions.showPrint) {
        if (!mButtonsElement) {
          mButtonsElement = $("<div class='is-grid-buttons'></div>");
          mElement.append(mButtonsElement);
          mElement.addClass("has-buttons");
        }

        // Clear existing
        mButtonsElement.children().remove();

        // Add buttons list
        var bl = $("<ul class='group'></ul>");
        mButtonsElement.append(bl);

        // Print
        if (mOptions.showPrint) {
          var e = $("<li><button class='is-button' icon='Print'>Print</button></li>");
          bl.append(e);
          button = $("button", e);
          button.click(function () {
            Print();
          });
        }

        // Finalise
        ApplyIcons($("button", bl));
      }
    }

    // ------------------------------
    // PUBLIC: The jQuery DIV Element
    // ------------------------------
    function Element() {
      return mElement;
    }

    // ----------------------------------------
    // PUBLIC: Add an item to the Content Cache
    // ----------------------------------------
    function CacheAdd(key, content) {
      mCache[key] = content;
    }

    // -------------------------------
    // PUBLIC: Clear the Content Cache
    // -------------------------------
    function CacheClear() {
      mCache = {};
    }

    // ---------------------------------------------------------
    // PUBLIC: Check to see if a key exists in the Content Cache
    // ---------------------------------------------------------
    function CacheExists(key) {
      return mCache[key] != undefined;
    }

    // ----------------------------------------------
    // PUBLIC: Remove an entry from the Content Cache
    // ----------------------------------------------
    function CacheRemove(key) {
      if (CacheExists(key)) delete mCache[key];
    }

    // ---------------------
    // PUBLIC: Clear Content
    // ---------------------
    function Clear() {
      // Initialise
      mContentHtmlFull = "";

      // Clear content
      // NOTE: Do not use jQuery as this then refers to the parent document and NOT the IFRAME document!
      try {
        var doc = mContentIframe[0].contentDocument;
        doc.open();
        doc.write("");
        doc.close();
      }
      catch (ex) {
        // Ignore
      }

      // Flags
      mLoaded = false;
    }

    // --------------------------------------------------------------
    // PUBLIC: Indicates whether this preview pane has content loaded
    // --------------------------------------------------------------
    function Loaded() {
      return mLoaded;
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Indicates whether this preview pane is currently loading content
    // ------------------------------------------------------------------------
    function Loading(value) {
      if (value === undefined) {
        return mLoading;
      }
      else {
        mLoading = (value == true);

        // Update
        UpdateElement();
      }      
    }

    // ---------------------------------------
    // PUBLIC: Load preview from a Web Service
    // ---------------------------------------
    function PreviewFromWebService(url, params) {
      // Clear (to avoid confusion)
      Clear();

      // Loading
      Loading(true);

      // Fetch
      $Api.GetDirect(url, params, {
        done: function (data, textStatus, xhr) {
          // ----
          // Done
          // ----
          var html = data;

          // Preview
          SetContent(html, false, {});

          // Loaded
          mLoaded = true;
        },

        fail: function (jqXHR) {
          // ----
          // Fail
          // ----
          SetContentErrorAjax(jqXHR);
        },

        always: function () {
          // ------
          // Always
          // ------
          Loading(false);          
        }
      });
    }

    // -----------------------------------------------------------------------------------
    // PUBLIC: Automatically provide a cached preview for a grid and associated collection
    // -----------------------------------------------------------------------------------
    function PreviewFromGridCollection(grid, collection, widgetEventId) {
      // Validate
      if (!collection.GetCacheKey) {
        //window.alert("Grid.PreviewFromGridCollection: Collection does not provide a GetCacheKey method (this is required regardless as to whether 'noCache' is set to true.");
        console.warn("Grid.PreviewFromGridCollection: Collection does not provide a GetCacheKey method (this is required regardless as to whether 'noCache' is set to true.");
        return;
      }
      else if (!collection.GetPreviewFetchParameters) {
        //window.alert("Grid.PreviewFromGridCollection: Collection does not provide a GetPreviewFetchParameters method.");
        console.warn ("Grid.PreviewFromGridCollection: Collection does not provide a GetPreviewFetchParameters method.");
        return;
      }

      // Get grid index
      var index = grid.ActiveDataRowListIndex();

      // No row selected
      if (index == -1) {
        Clear();
        return;
      }

      // Get Cache Key
      var key = collection.GetCacheKey(index);

      // Load from cache?
      if (CacheExists(key)) {
        SetContentFromCache(key, false, {});
        return;
      }

      // Clear (to avoid confusion)
      Clear();

      // Delay load for 150ms (so we don't fetch if User is quickly moving up and down the grid which would end up queuing requests)
      var ti = setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        // Row changed?
        if (index != grid.ActiveDataRowListIndex()) return;

        // Loading
        Loading(true);

        // Fetch
        widget.GetString(widgetEventId, collection.GetPreviewFetchParameters(index),
          function (data) {
            // ----
            // Done
            // ----
            var html = data;

            // Cache
            if (!mOptions.noCache) CacheAdd(key, html);

            // Preview
            // NOTE: Since this is asynchronous, check that item has not changed (e.g.,grid row changed)
            if (key == collection.GetCacheKey(grid.ActiveDataRowListIndex())) {
              SetContent(html, false, {});

              // Loaded
              mLoaded = true;
            }
            else {
              // Changed so do not preview
            }

            Loading(false);
          },

          function (error) {
            // ----
            // Fail
            // ----
            SetContentError(error);

            Loading(false);
          });
      }, 150);
    }

    // ------------------------------------------------
    // PUBLIC: Resize from Parent (for when not docked)
    // ------------------------------------------------
    function ResizeFromParent() {
      // E.g., from the Log form, Fee page
      //mElement.css({ width: "100%", height: "100%", overflow: "visible", display: "inline-block", border: "4px solid green" });
      mElement.css({ width: "100%", height: "100%", overflow: "visible", display: "block" });
      mContentIframe.css({ width: "100%", height: "100%", overflow: "auto" });
    }

    // ---------------------
    // Set Content Resources
    // ---------------------
    var SetContentResources = {
      cssSummaryPage2: true,
      formatAsSummaryPage2: false,

      // Only applicable when not complete HTML
      summaryPage2Blocks: false,
    };

    // --------------------------
    // PUBLIC: Set IFRAME Content
    // --------------------------
    function SetContent(html, htmlComplete, resources) {
      // Extend options
      var o = $.extend({}, SetContentResources, resources);

      // Loaded
      mLoaded = true;
      Loading(false);

      // Initialise
      mContentHtmlFull = "";

      // Complete HTML supplied?
      if (!htmlComplete) {
        if (html && html.toUpperCase().indexOf("<HTML") != -1) {
          htmlComplete = true;
          console.log("widget.UI.PreviewPane.SetContent: Complete HTML detected so 'htmlComplete=false' flag has been ignored");
        }
      }

      // Add required resources
      var resourcesHtml = "";
      if (o.cssSummaryPage2) {
        var suffix = "";
        if (window.$App && $App.Version) {
          suffix = "?v=" + $App.Version();
        }
        var cssPath = "";
        switch (widget.GetHostingContext()) {
          case "WebInternal":
          case "WebExternal":
            cssPath = Runtime_WebRoot + "Content/SummaryPage2/";
            break;

          default:
            cssPath = widget.Options.templatesPath + "/";
            break;
        }

        if (window._V6) {
          // V6
          if (window.parent && window.parent.$App) {
            resourcesHtml += "<link rel='stylesheet' type='text/css' href='" + window.parent.$Runtime.WebRoot() + "Content/ThemedStyleSheets?bundle=summarypage2&v=" + window.parent.$App.Version() + "'></link>";
          }
          else {
            resourcesHtml += "<link rel='stylesheet' type='text/css' href='" + cssPath + "summarypage_2.css" + suffix + "'></link>";
          }
        }
        else {
          // V4
          resourcesHtml += "<link rel='stylesheet' type='text/css' href='" + cssPath + "summarypage_2.css" + suffix + "'></link>";
        }

        switch (widget.GetHostingContext()) {
          case "HtmlViewer":
            break;

          default:
            resourcesHtml += "<link rel='stylesheet' type='text/css' href='" + cssPath + "summarypage_2_web.css" + suffix + "'></link>";
        }
      }

      // Normalise HTML for Preview
      if (window.$App) html = $App.NormaliseHtmlPreview(html);

      // Smart background colouring
      if (mOptions.smartBackgroundColour) {
        if (html.indexOf("is-summarypage-blocks") == -1) {
          mContentIframe.css({ "background-color": "" });
        }
        else {
          // Summary page 2 blocks
          if (window.top && window.top.$App && window.top.$App.SettingsDevice && window.top.$App.SettingsDevice().BetaStyling) {
            // BETA styling
            mContentIframe.css({ "background-color": "#fdfdfd" });
          }
          else {
            mContentIframe.css({ "background-color": "#808080" });
          }
        }
      }

      // Set reference to Content Window
      var win = mContentIframe[0].contentWindow;

      // Write content
      // NOTE: Do not use jQuery as this then refers to the parent document and NOT the IFRAME document!
      if (!htmlComplete) {
        mContentHtmlFull += "<!doctype html>";
        mContentHtmlFull += "<html";
        if (o.summaryPage2Blocks) mContentHtmlFull += " class='is-summarypage-2 is-summarypage-blocks'";
        mContentHtmlFull += ">";
        mContentHtmlFull += "<head>";
        if (!resourcesHtml) console.warn("No Resources!\n\no.cssSummaryPage2=" + o.cssSummaryPage2);
        mContentHtmlFull += resourcesHtml;
        mContentHtmlFull += "</head>";
        mContentHtmlFull += "<body style='margin:0;padding:0'"; // Cancel out any body padding etc from the stylesheet
        if (o.summaryPage2Blocks) mContentHtmlFull += " class='is-summarypage-blocks'";
        mContentHtmlFull += ">";
        if (o.formatAsSummaryPage2) mContentHtmlFull += "<div class='is-summarypage-2'>";
      }
      mContentHtmlFull += html;
      if (!htmlComplete) {
        if (o.formatAsSummaryPage2) mContentHtmlFull += "</div>";
        mContentHtmlFull += "</body>";
        mContentHtmlFull += "</html>";
      }
      var doc = mContentIframe[0].contentDocument;
      doc.open();
      doc.write(mContentHtmlFull);
      doc.close();

      // Handle Application Shortcuts
      if (mOptions.handleApplicationShortcuts) {
        if (mOptions.applicationShortcutHandler) {
          // Let the HTML Widget handle Application Shortcuts, e.g., Task Manager Workflow folder needs to send 'Workflow' Form Actions via the global handler
          // NOTE: Code similar to $Ash.HandleDocument
          var doc2 = $(doc);
          doc2.off("click", "a[href^='app:'],a[href^='APP:']"); // Remove existing, e.g., when refreshing an HTML Widget's content
          doc2.on("click", "a[href^='app:'],a[href^='APP:']", function () {
            var e = $(this);
            mOptions.applicationShortcutHandler(e.attr("href"));
            // Prevent link from navigating
            return false;
          });
        }
        else if (window.parent.$Ash) {
          // finPOWER Connect Cloud detected
          window.parent.$Ash.HandleIframe(mContentIframe[0], mOptions.formActionHandler);
        }
        else {
          if (top.$Ash) {
            // finPOWER Connect Cloud detected
            // Use Parent functionality (probably being used from an HTML Widget's Summary Page)
            console.log("Set Content will handle Application Shortcuts using it's parent since no handler ($Ash) is available.");
            window.$Ash = top.$Ash;
            window.$Ash.HandleIframe(contentIframe[0], mOptions.formActionHandler);
          }
          else {
            if (top.__webview2) {
              // WebView2 running in finPOWER Connect desktop
              var doc2 = $(doc);
              doc2.off("click", "a[href^='app:'],a[href^='APP:']"); // Remove existing, e.g., when refreshing an HTML Widget's content
              doc2.on("click", "a[href^='app:'],a[href^='APP:']", function () {
                var e = $(this);

                top._widget.ExecuteApplicationShortcutUrl(e.attr("href"));

                // Prevent link from navigating
                return false;
              });
            }
            else {
              //window.alert("Preview Pane cannot handle Application Shortcuts since no handler ($Ash) is available.");
            }
          }
        }

        // F1 Help
        // NOTE: Only when running in finPOWER Connect Cloud
        try {
          if (window.top && window.top.$App) {
            win.onkeydown = function (e) {
              if (e.keyCode == 112) {
                //TODO: With widgets, we could perhaps set a doc._helpid property that could be picked up here
                var helpId = "";

                window.top.$App.ShowHelp(helpId);

                return false;
              }
            };
          }
        }
        catch (ex) {
          console.warn("widget.UI.PreviewPane: Failed to handle F1.\n\n" + ex);
        }
      }

      // Resize to fit (e.g., Log HTML Widget for top part of Email page)
      // NOTE: This relies on the content being loaded when the page containing this control is visible
      if (mOptions.resizeToFit) {
        var e = $("div.is-summarypage-2", mContentIframe[0].contentDocument);
        if (e.length != 0) {
          mElement.css("min-height", (e.height() + mOptions.resizeToFitAdditionalHeight) + "px");

          // Resize again, just in case styles were loading
          var ti = window.setTimeout(function () {
            window.clearTimeout(ti);
            ti = null;

            mElement.css("min-height", (e.height() + mOptions.resizeToFitAdditionalHeight) + "px");
          }, 1000);
        }
      }

      // BETA styling
      if (window.top && window.top.$App && window.top.$App.SettingsDevice && window.top.$App.SettingsDevice().BetaStyling) {
        try {
          $("html", mContentIframe[0].contentDocument).addClass("is-beta-styling");
        }
        catch (ex) {
          console.warn("PreviewPane.SetContent: failed to add beta styling to document.")
        }
      }
    }

    // -------------------------------------------------------
    // PUBLIC: Set IFRAME Content to display error information
    // -------------------------------------------------------
    function SetContentError(message, details) {
      // Build HTML
      var html = "";
      html += "<div class='is-summarypage-2'>";
      html += "<div class='is-template-message'>";
      html += "<div class='is-template-message-error'>";
      html += HtmlEncode(message);
      if (details) {
        html += "<p>" + HtmlEncode(details) + "</p>";
      }
      html += "</div>";
      html += "</div>";
      html += "</div>";

      // Set content
      SetContent(html, false);
    }

    // ------------------------------------------------------------
    // PUBLIC: Set IFRAME Content to display error information
    // ------------------------------------------------------------
    function SetContentErrorAjax(jqXHR) {
      var data;
      var message = "";
      var messageInternal = "";

      // Extract error details
      try {
        data = $.parseJSON(jqXHR.responseText);
        if (data.Message) message = data.Message;
        if (data.InternalMessage) messageInternal = data.InternalMessage;
      }
      catch (e) {
      }

      // Set content
      SetContentError(message, messageInternal);
    }

    // ----------------------------------------------
    // PUBLIC: Set IFRAME Content from a Cached value
    // ----------------------------------------------
    function SetContentFromCache(key, htmlComplete, resources) {
      if (mCache[key] === undefined) {
        SetContent("Item '" + key + "' does not exist in the Content Cache.", false, {});
      }
      else {
        SetContent(mCache[key], htmlComplete, resources);
      }
    }

    // -----------------------------------
    // PUBLIC: Show the preview in a popup
    // -----------------------------------
    function ShowPreviewInPopup() {
      // Still loading?
      if (mLoading || !mLoaded || !mContentHtmlFull) return;

      // Show (force to be windowed so on mobile devices it looks different to normal windows)
      var modal = $UI.CommonDialog().ShowHtml("Preview", mContentHtmlFull, { forceWindowed: true, popup: false });

      // Redirect all 'FormAction' Application Shortcuts to this control's hosting form
      var parentModal = $UI.FindParentModal(mElement);
      if (parentModal && parentModal.OnAction()) {
        modal.OnAction(parentModal.OnAction());
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.PreviewPane.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // ============
    // Print method
    // ============
    function Print() {
      try {
        mContentIframe[0].contentWindow.print();
      }
      catch (ex) {
        window.alert(ex);
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "PreviewPane",

      //CacheAdd: CacheAdd,
      CacheClear: CacheClear,
      CacheExists: CacheExists,
      CacheRemove: CacheRemove,

      Clear: Clear,
      Element: Element,

      Loaded: Loaded,
      Loading: Loading,

      Print: Print,
      PreviewFromGridCollection: PreviewFromGridCollection,
      //PreviewFromWebService: PreviewFromWebService,

      ResizeFromParent: ResizeFromParent,

      SetContent: SetContent,
      SetContentError: SetContentError,
      //SetContentErrorAjax: SetContentErrorAjax,
      //SetContentFromCache: SetContentFromCache,

      //ShowPreviewInPopup: ShowPreviewInPopup,

      Visible: Visible,
      VisibleRow: VisibleRow,
    };

    return _self;
  }



  // ============================
  // PUBLIC: Grouping List object
  // ============================
  function GroupingList(e, options) {

    // NOTE: This is based on the implementation in ParametersHost hence code may look a little different to other controls

    var mElement;
    var mElementRow;
    var mLabelElement;
    var mList;
    var mOptions;
    var mValue;

    // Sub-controls and properties
    var C = {
      lstLeft: null,
      lstRight: null,
      ulLeft: null,
      ulRight: null,
      groupingItems: [],
      groupedItems: [],
    };

    // Extend options with defaults
    GroupingListDefaults = {
      allowMoveUpDown: true,
      allowPageBreak: false,
      indentRightList: false,
      showPageBreakButton: false,

      readOnly: false,
      autoReadOnly: true,

      visible: true,

      onChange: null,
    };
    mOptions = $.extend({}, GroupingListDefaults, options);

    // Get Element and validate (may be element or id)
    // NOTE: The parent element is likely to be a div element
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.GroupingList: Parent element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Add elements for layout
    var layout = $("<span id='" + id + "' class='is-widget-groupinglist'><div id='" + id + "Left' class='left'></div><div id='" + id + "Right' class='right'></div></span>");
    mElement.append(layout);

    // Create elements (within layout)
    C.lstLeft = $("#" + id + "Left", layout);
    C.lstRight = $("#" + id + "Right", layout);

    // Configure Left List
    C.ulLeft = $("<ul tabindex='-1' class='is-no-select'></ul>");
    C.lstLeft.append(C.ulLeft);

    // Configure Right List
    C.ulRight = $("<ul tabindex='-1' class='is-no-select'></ul>");
    C.lstRight.append(C.ulRight);

    // Set value (just a dummy call really)
    GroupingList_UpdateValue("");

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Classes
      mElement.addClass("is-widget-groupinglist");

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
      }
      else {
        mElement.removeClass("is-readonly");
      }

      // Visibility
      if (mOptions.visible) {
        mElement.show();
        if (mLabelElement) mLabelElement.show();
      }
      else {
        mElement.hide();
        if (mLabelElement) mLabelElement.hide();
      }
    }

    function GroupingList_UpdateValue(value) {
      var groupingItems = C.groupingItems;
      var groupedItems = C.groupedItems;

      if (value) {
        var list = value.split("|");
        for (var i = 0; i < list.length; i++) {
          // Split out page break?
          var name = list[i];
          var n = name.indexOf(";");
          var pageBreak = false;
          if (n !== -1) {
            pageBreak = true;
            name = name.substr(0, n);
          }

          // Add grouping
          for (var j = 0; j < groupingItems.length; j++) {
            var gi = groupingItems[j];
            if (name.toUpperCase() === gi.name.toUpperCase()) {
              gi.groupBy = true;
              gi.pageBreakAfter = pageBreak;
              if (!groupedItems.includes(gi)) {
                groupedItems.push(gi);
              }
            }
          }
        }
      }

      // Update Lists
      GroupingList_UpdateListLeft();
      GroupingList_UpdateListRight();
    }

    function GroupingList_UpdateListLeft() {
      // Clear existing
      C.ulLeft.children().remove();

      // Rebuild list
      for (var i = 0; i < C.groupingItems.length; i++) {
        var gi = C.groupingItems[i];
        if (!gi.groupBy) {
          var li = $("<li index='" + gi.index + "'></li>");
          li.html("<label>" + HtmlEncode(gi.caption) + "</label>");

          li.append("<button action='add'></button>");

          C.ulLeft.append(li);
        }
      }
      GroupingList_UpdateListEvents(false);
    }

    function GroupingList_UpdateListRight(selectedIndex) {
      // Clear existing
      C.ulRight.children().remove();

      // Rebuild list
      for (var i = 0; i < C.groupedItems.length; i++) {
        var gi = C.groupedItems[i];
        var li = $("<li order='" + i + "' index='" + gi.index + "'><span></span><label>" + widget.UI.HtmlEncode(gi.caption) + "</label></li>");
        li.append("<button action='remove' tabindex='0'></button>");
        if (mOptions.allowMoveUpDown) {
          li.append("<button action='moveup' tabindex='0'></button>");
          li.append("<button action='movedown' tabindex='0'></button>");
        }
        if (mOptions.showPageBreakButton) {
          var pb = $("<button action='pagebreak' tabindex='0' title='Page break before'></button>");
          pb.css("background-image", "url(" + widget.GetIconUrl("PageBreak", 16) + ")");
          if (gi.pageBreakAfter) pb.addClass("checked");

          li.append(pb);
        }
        //if (selectedIndex === gi.index) li.addClass("selected");
        if (selectedIndex === i) li.addClass("selected");

        C.ulRight.append(li);
      }
      GroupingList_UpdateListRightIndent();
      GroupingList_UpdateListEvents(true);
    }

    function GroupingList_UpdateListRightIndent() {
      // Redo right list indenting (without rebuilding the list)
      var lis = $("li > span", C.ulRight);
      for (var i = 0; i < lis.length; i++) {
        var li = $(lis[i]);
        if (mOptions.indentRightList) {
          li.css("padding-left", (i * 8) + "px");
        }
      }
    }

    function GroupingList_UpdateListEvents(isRightList) {
      if (mOptions.readOnly) return;

      // Initialise
      var ul = isRightList ? C.ulRight : C.ulLeft;
      var lis = $("li", ul);

      // Click to select
      lis.click(function (e) {
        GroupingList_SelectItem(ul, $(this).attr("index"));
      });

      // Left/ Right list-specific
      if (isRightList) {
        // Right
        $("button", lis).click(function (e) {
          var li = $(this).parent();
          var index = li.attr("index");
          var order = parseInt(li.attr("order"));
          var action = $(this).attr("action");

          switch (action) {
            case "remove":
              // Remove
              if (!mOptions.readOnly) GroupingList_MoveLeft(index);
              break;

            case "pagebreak":
              // Toggle page break after
              if (!mOptions.readOnly) {
                var gi = C.groupingItems[index];
                gi.pageBreakAfter = !gi.pageBreakAfter;
                if (gi.pageBreakAfter) {
                  $(this).addClass("checked");
                }
                else {
                  $(this).removeClass("checked");
                }
                GroupingList_UpdateParameterValue();
              }
              break;

            case "moveup":
              // Move up
              if (!mOptions.readOnly) {
                if (order > 0) {
                  var a1 = C.groupedItems[order];
                  var a2 = C.groupedItems[order - 1];
                  C.groupedItems[order] = a2;
                  C.groupedItems[order - 1] = a1;

                  GroupingList_UpdateListRight(order - 1);
                  GroupingList_UpdateParameterValue();
                }
              }
              break;

            case "movedown":
              if (!mOptions.readOnly) {
                if (order < C.groupedItems.length - 1) {
                  var a1 = C.groupedItems[order];
                  var a2 = C.groupedItems[order + 1];
                  C.groupedItems[order] = a2;
                  C.groupedItems[order + 1] = a1;

                  GroupingList_UpdateListRight(order + 1);
                  GroupingList_UpdateParameterValue();
                }
              }
              break;

            default:
              window.alert("Unhandled button acton '" + action + "'");
              break;
          }
        });
        lis.bind("dblclick", function () {
          if (!mOptions.readOnly) GroupingList_MoveLeft($(this).attr("index"));
        });
      }
      else {
        // Left
        $("button", lis).click(function (e) {
          if (!mOptions.readOnly) GroupingList_MoveRight($(this).parent().attr("index"));
        });
        lis.bind("dblclick", function () {
          if (!mOptions.readOnly) GroupingList_MoveRight($(this).attr("index"));
        });
      }

      // Keyboard functionality
      ul.unbind("keydown.list");
      ul.bind("keydown.list", function (e) {
        // Find item indexes
        var lis = $("li", ul);
        var firstIndex = -1;
        var selIndex = -1;
        var nextIndex = -1;
        var prevIndex = -1;
        var lastIndex = -1;

        for (var i = 0; i < lis.length; i++) {
          var li = $(lis[i]);
          var index = li.attr("index");

          if (firstIndex === -1) firstIndex = index;
          lastIndex = index;
          if (nextIndex === -1 && selIndex != -1) nextIndex = index;
          if (selIndex === -1 && li.hasClass("selected")) selIndex = index;
          if (selIndex === -1) prevIndex = index;
        }

        switch (e.keyCode) {
          case 13: // Enter
            break;

          case 35: // End
            if (lis.length > 0) GroupingList_SelectItem(ul, lastIndex, true);
            e.preventDefault();
            return false;

          case 36: // Home
            GroupingList_SelectItem(ul, firstIndex, true);
            e.preventDefault();
            return false;

          case 38: // Cursor Up
            if (prevIndex !== -1) GroupingList_SelectItem(ul, prevIndex, true);
            e.preventDefault();
            return false;


          case 40: // Cursor Down
            if (nextIndex !== -1) GroupingList_SelectItem(ul, nextIndex, true);
            e.preventDefault();
            return false;
        }
      });
    }

    function GroupingList_MoveRight(index) {
      // Remove element from left list
      var li = $("li[index='" + index + "']", C.ulLeft);
      li.remove();

      // Move to right list
      var gi = C.groupingItems[index];
      gi.groupBy = true;
      gi.pageBreakAfter = false;
      C.groupedItems.push(gi);
      GroupingList_UpdateListRight(index);

      // Update Parameter Value
      GroupingList_UpdateParameterValue();
    }

    function GroupingList_MoveLeft(index) {
      // Remove element from left list
      var li = $("li[index='" + index + "']", C.ulRight);
      li.remove();

      // Move to left list
      var gi = C.groupingItems[index];
      gi.groupBy = false;
      var tempArr = [];
      for (var i = 0; i < C.groupingItems.length; i++) {
        var gi = C.groupingItems[i];
        if (gi.groupBy) tempArr.push(gi);
      }
      C.groupedItems = tempArr;
      //$Runtime.ArrayRemove(C.groupedItems, gi);
      GroupingList_UpdateListLeft(index);
      GroupingList_UpdateListRightIndent();

      // Update Parameter Value
      GroupingList_UpdateParameterValue();

      // Select removed item in left list
      GroupingList_SelectItem(C.ulLeft, index);
    }

    function GroupingList_SelectItem(ul, index, fromKb) {
      $("li", ul).removeClass("selected");
      var li = $("li[index='" + index + "']", ul);
      li.addClass("selected");
      if (fromKb) li.ScrollElementIntoView(true);
    }

    function GroupingList_UpdateParameterValue() {
      var s = "";
      for (var i = 0; i < C.groupedItems.length; i++) {
        var gi = C.groupedItems[i];
        if (s) s += "|";
        s += gi.name;
        if (gi.pageBreakAfter) s += ";True";
      }
      mValue = s;
    }


    // --------------------------------
    // PUBLIC: The jQuery Div Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // ---------------------
    // PUBLIC: List property
    // ---------------------
    function List(value) {
      if (value === undefined) {
        // Get
        return mList;
      }
      else {
        // Set
        mList = value;

        C.groupingItems = [];
        var list = widget.ArrayFromCsvString(mList ? mList + "" : "");

        // Add items
        for (var i = 0; i < list.length; i++) {
          // Split out caption?
          var name = list[i];
          var n = name.indexOf("[");
          var caption = name;
          if (n != -1) {
            caption = name.substr(0, n);
            name = name.substr(n + 1);
            name = name.substr(0, name.length - 1);
          }

          // Add item
          C.groupingItems.push({
            index: i,
            name: name,
            caption: caption,
            groupBy: false,
            pageBreakAfter: false,
            selected: false,
          });
        }

        // Update Lists
        GroupingList_UpdateListLeft();
        GroupingList_UpdateListRight();
      }
    }

    // ---------------------------
    // PUBLIC: Set List from Array
    // ---------------------------
    function ListFromArray(list) {
      List(widget.ArrayToCsvString(list));
    }

    // ----------------------------
    // PUBLIC: Read-Only property
    // ----------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        return mValue;
      }
      else {
        // Set
        mValue = value;

        // Refresh
        GroupingList_UpdateValue(mValue);
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.GroupingList.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "GroupingList",

      Element: Element,

      List: List,
      ListFromArray: ListFromArray,
      ReadOnly: ReadOnly,
      Value: Value,
      Visible: Visible,
      VisibleRow: VisibleRow,
    };

    return _self;
  }



  // ==========================
  // PUBLIC: HTML Editor object
  // ==========================
  function HtmlEditor(e, options) {

    var mElement;
    var mElementContent;
    var mElementContentSource;
    var mElementRow;
    var mElementToolbar;
    var mOptions;
    var mTagsList = [];
    var mTagsListElement;
    var mTagsListElementParent;
    var mTagsListVisible = false;
    var mInTagsClick = false;
    var mTextOriginal;
    var mTextBoxSource;

    // Extend options with defaults
    HtmlEditorDefaults = {
      spellCheck: false,

      readOnly: false,
      autoReadOnly: true,

      plainText: false,
      showHtmlMarkup: false, // true means to show the HTML markup, i.e., the tags
      visible: true,

      onChange: null,
    };
    mOptions = $.extend({}, HtmlEditorDefaults, options);

    // Get Element and validate (may be element or id)
    // NOTE: The parent element is likely to be a div element
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.HtmlEditor: Parent element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Create elements
    mElementToolbar = $("<div class='toolbar'></div>");
    mElementContent = $("<div class='content'></div>");
    mElementContentSource = $("<div class='content source'><input/></div>");
    mElement.append(mElementToolbar);
    mElement.append(mElementContent);
    mElement.append(mElementContentSource);
    mTagsListElement = $("<div class='is-textbox-tagslist' style='display:none'></div>");
    mElement.append(mTagsListElement);
    mTextBoxSource = TextBox($("input", mElementContentSource), {
      changeWhileTyping: true,
      multiLine: true,
      visible: false,

      onChange: function (sender, e) {
        // Handled
        if (e) e.ChangeHandled = true;

        // Keep HTML view in in sync
        mElementContent.html(mTextBoxSource.Text());

        // Notify
        if (mOptions.onChange) {
          var e = { ChangeHandled: false };
          if (mOptions.onChange) mOptions.onChange(_self, e);
        }
      }
    });
    mTextBoxSource.WrapperElement().css({ "position": "absolute", "left": "0", "right": "0", "top": "0", "bottom": "0" });
    mTextBoxSource.Element().css("border", "none");

    // Keep source and HTML previews in sync
    mElementContent[0].addEventListener("input", function () {
      if (!mOptions.readOnly) {
        mTextBoxSource.Text(mElementContent.html());

        // Notify
        if (mOptions.onChange) {
          var e = { ChangeHandled: false };
          if (mOptions.onChange) mOptions.onChange(_self, e);
        }
      }
    });


    // Initialise
    UpdateElement();


    // ---------------------------
    // PRIVATE: Update the Element
    // ---------------------------
    function UpdateElement() {
      // CSS
      mElement.addClass("is-html-editor");

      // Read-only?
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElementContent.attr("contenteditable", false);
      }
      else {
        mElement.removeClass("is-readonly");
        mElementContent.attr("contenteditable", true);
      }
      mTextBoxSource.ReadOnly(mOptions.readOnly);

      // Show preview or raw HTML
      if (mOptions.showHtmlMarkup || mOptions.plainText) {
        mTextBoxSource.Visible(true);
        mElementContentSource.show();
        mElementContentSource.css("display", ""); // jQuery Fix
        mElementContent.hide();
      }
      else {
        mTextBoxSource.Visible(false);
        mElementContentSource.hide();
        mElementContent.show();
        mElementContent.css("display", ""); // jQuery Fix
      }

      // Toolbar
      mElementToolbar.children().remove();
      if (mOptions.plainText) {
        // HTML not allowed
        mElementToolbar.hide();
      }
      else {
        var ul = $("<ul class='is-no-select'></ul>");
        ul.click(function (e) {
          ExecuteCommand($(e.target).attr("command"));
        });

        if (mOptions.showHtmlMarkup) {
          ul.append("<li command='toggleHtmlMarkup' style='font-size:11px;overflow:hidden'>Hide&nbsp;HTML&nbsp;Markup</li>");
        }
        else {
          ul.append("<li command='toggleHtmlMarkup' style='font-size:11px;overflow:hidden'>Show&nbsp;HTML&nbsp;Markup</li>");
        }
        if (!mOptions.showHtmlMarkup && !mOptions.readOnly) {
          ul.append("<li command='bold' title='Bold'></li>");
          ul.append("<li command='italic' title='Italic'></li>");
          ul.append("<li command='underline' title='Underline'></li>");
          ul.append("<li command='removeformat' title='Remove formatting from selection'></li>");
          ul.append("<li command='clean' title='Remove all HTML formatting'></li>");

          ul.append("<li title='Text formatting' style='overflow:hidden'><select command-name='text-style' tabindex='-1'><option>-- Style --</option><option value='p'>Normal</option><option value='h1'>Heading 1</option><option value='h2'>Heading 2</option><option value='h3'>Heading 3</option><option value='h4'>Heading 4</option></select></li>");

          ul.append("<li command='justifyleft' title='Justify left'></li>");
          ul.append("<li command='justifycenter' title='Justify centre'></li>");
          ul.append("<li command='justifyright' title='Justify right'></li>");

          ul.append("<li command='insertorderedlist' title='Numbered list'></li>");
          ul.append("<li command='insertunorderedlist' title='Bullet list'></li>");

          ul.append("<li command='outdent' title='Reduce indentation'></li>");
          ul.append("<li command='indent' title='Increase indentation'></li>");

          ul.append("<li command='createlink' title='Hyperlink'></li>");
        }

        mElementToolbar.append(ul);
        mElementToolbar.show();

        // Other events
        $("select", ul).change(function (e) {
          var el = $(this);
          var value = el.val();
          el.prop("selectedIndex", 0);

          if (value && !value.startsWith("-")) {
            switch ($(this).attr("command-name")) {
              case "text-style":
                ExecuteCommand("formatblock", value);
                break;
            }
          }
        });
      }
    }

    // ----------------------------------
    // PRIVATE: Execute a toolbar command
    // ----------------------------------
    function ExecuteCommand(command, value) {
      if (!command) return;

      var oDoc = mElementContent[0];

      switch (command) {
        case "clean":
          widget.UI.MsgBoxConfirm("Remove all HTML formatting?", {}, function () {
            var s = mElementContent.text();
            Text(s);
          });
          break;

        case "createlink":
          var link = window.prompt("Hyperlink", 'https:\/\/');
          if (link && link != "https://") {
            document.execCommand(command, false, link);
          }
          break;

        case "toggleHtmlMarkup":
          ShowHtmlMarkup(!mOptions.showHtmlMarkup);
          if (mOptions.showHtmlMarkup) {
            //mTextBoxSource.Focus(); // Don't focus, otherwise it selects all text
          }
          else {
            mElementContent.focus();
          }
          break;

        default:
          document.execCommand(command, false, value);
          oDoc.focus();
      }
    }

    // -------------------------------------------------------------------
    // PUBLIC: Define an array of Tags from a Code Description List object
    // -------------------------------------------------------------------
    function TagsListDefineFromCodeDescriptionList(codeDescriptionList) {
      var tagsList = [];

      if (codeDescriptionList) {
        for (var i = 0; i < codeDescriptionList.length; i++) {
          var item = codeDescriptionList[i];
          tagsList.push({ caption: item.Code, value: "[" + item.Code + "]" });
        }
      }

      TagsListDefine(tagsList);
    }

    // -------------------------------------------------------------------------------
    // PUBLIC: Define an array of Tags ({caption: "", value: ""}) to show when focused
    // -------------------------------------------------------------------------------
    function TagsListDefine(tagsList) {
      mTagsList = tagsList;

      // Build HTML element
      if (mTagsList && mTagsList.length != 0) {
        mTagsListElement.hide();
        mTagsListVisible = false;
        mElement.removeClass("tags-visible");

        mTagsListElement.children().remove();

        mTagsListElementParent = mTagsListElement.parent();

        var ul = $("<ul class='is-no-select'></ul>");
        var lastPrefix = "", lastPrefixIndex = -1;
        var colours = ["#ccf5f3", "#8c6700", "#ffe0e0", "#e4e0fb", "#daf5e8", "#caeefe", "#f8f8f8", "#977c00", "#5f8603"];
        var bgcolours = ["#20b2aa", "#ffd561", "#ff6666", "#7b68ee", "#47ce8e", "#02A8F3", "#bdbdbd", "#ffe87c", "#ccfb5d"];
        for (var i = 0; i < tagsList.length; i++) {
          var tag = mTagsList[i];          
          var li = $("<li></li>");

          // For clarity, it the caption contains a dot (e.g., "Client.Name") then style differently either side
          var n = tag.caption.indexOf(".");
          if (n == -1) {
            li.text(tag.caption);
          }
          else {
            var left = tag.caption.substr(0, n);
            if (left != lastPrefix) {
              lastPrefix = left;
              lastPrefixIndex += 1;
              if (lastPrefixIndex >= colours.length) lastPrefixIndex = 0;
            }
            var right = widget.SplitWordsAtCapitals(tag.caption.substr(n + 1));

            // NOTE: Assign a CSS class just in case someone wants to customise their own colours
            li.html("<span class='is-tag-group-" + lastPrefixIndex + "' style='font-weight:bold; display:inline-block; margin-left:-2px; padding:0 2px 0 2px; border-radius:4px 0 0 4px; color:" + colours[lastPrefixIndex] + "; background-color: " + bgcolours[lastPrefixIndex] + ";'>" + left + "</span>" + "." + "<span>" + right + "</span>");
          }

          li.attr("value", tag.value);
          ul.append(li);
        }
        mTagsListElement.append(ul);
        
        // Handle events
        ul.mousedown(function (e) {
          mInTagsClick = true;
        })
        ul.mouseup(function (e) {
          mInTagsClick = false;
        });
        ul.click(function (e) {
          var value = $(e.target).attr("value") || $(e.target).parent().attr("value");
          if (value) {
            ExecuteCommand("insertText", value);
          }
        });
        mTagsListElementParent.focusin(TagsListShow);
        mTagsListElementParent.focusout(TagsListHide);
      }
      else {
        if (!mOptions.tagsListElement) {
          mTagsListElement.hide();
          mTagsListVisible = false;
          mElement.removeClass("tags-visible");
        }
      }
    }

    // -----------------------
    // PUBLIC: Show Tags List
    // -----------------------
    function TagsListShow() {
      if (mTagsListElement && !mOptions.readOnly) {
        // Show
        mTagsListVisible = true;
        mElement.addClass("tags-visible");
        mTagsListElement.show();
      }
    }

    // -----------------------
    // PUBLIC: Hide Tags List
    // -----------------------
    function TagsListHide() {
      if (mTagsListElement) {
        if (mInTagsClick) {
          // Do nothing
        }
        else {
          mTagsListElement.hide();
          mTagsListVisible = false;
          mElement.removeClass("tags-visible");
        }
      }
    }

    // -------------------------
    // PRIVATE: Insert Tag value
    // -------------------------
    function TagInsert(value) {
      if (!mOptions.readOnly) {
        ExecuteCommand("insertText", "abc");//value);
      }
    }

    // ------------------------------
    // PUBLIC: The jQuery DIV Element
    // ------------------------------
    function Element() {
      return mElement;
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // --------------------------
    // PUBLIC: PlainText property
    // --------------------------
    function PlainText(value) {
      if (value === undefined) {
        // Get
        return mOptions.plainText;
      }
      else {
        // Set
        if (value != mOptions.plainText) {
          mOptions.plainText = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: ShowHtmlMarkup property
    // -------------------------------
    function ShowHtmlMarkup(value) {
      if (value === undefined) {
        // Get
        return mOptions.showHtmlMarkup;
      }
      else {
        // Set
        if (value != mOptions.showHtmlMarkup) {
          mOptions.showHtmlMarkup = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        if (mOptions.plainText || mOptions.showHtmlMarkup) {
          return mTextBoxSource.Text();
        }
        else {
          return mElementContent.html();
        }
      }
      else {
        // Set
        mTextBoxSource.Text(value);
        mElementContent.html(value);
        mTextOriginal = value;
      }
    }

    // ------------------------------------------------
    // PUBLIC: Resize from Parent (for when not docked)
    // ------------------------------------------------
    function ResizeFromParent() {
      // E.g., from the Log form, Fee page
      mElement.css({ width: "100%", height: "100%", overflow: "visible", display: "block" });
      mContentIframe.css({ width: "100%", height: "100%", overflow: "auto" });
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.HtmlEditor.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElementContent.focus();
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "HtmlEditor",

      AutoReadOnly: AutoReadOnly,
      Element: Element,
      Focus: Focus,

      ReadOnly: ReadOnly,
      ResizeFromParent: ResizeFromParent,

      PlainText: PlainText,
      ShowHtmlMarkup: ShowHtmlMarkup,

      TagsListDefine: TagsListDefine,
      TagsListDefineFromCodeDescriptionList: TagsListDefineFromCodeDescriptionList,
      TagsListHide: TagsListHide,
      TagsListShow: TagsListShow,
      Text: Text,

      Visible: Visible,
      VisibleRow: VisibleRow,
    };

    return _self;
  }



  // ===============================
  // PUBLIC: PromptUpdateList object
  // ===============================
  function PromptUpdateList(options) {
    var mList = [];
    var mElement;
    var mOptions;

    // Extend options with defaults
    PromptUpdateListDefaults = {
      caption: "Update the following?",
      onAccept: null,
      onCancel: null,
    };
    if (options === undefined) options = {};
    mOptions = $.extend({}, PromptUpdateListDefaults, options);

    // ---------------------------
    // PUBLIC: Show for an Element
    // ---------------------------
    function Show(parentElement, list) {
      // Find parent element (may be a control with an Element property)

      if (parentElement.Element) parentElement = parentElement.Element();

      // Append popup
      if (mElement) {
        mElement.children().remove();
      }
      else {
        mElement = $("<div class='is-prompt-update-list'></div>");
        $(parentElement).after(mElement);
      }

      // Caption
      mElement.append("<label>" + HtmlEncode(mOptions.caption) + "</label>");

      // Create List
      var ul = $("<ul></ul>");
      mElement.append(ul);
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        var li = $("<li><b>" + HtmlEncode(item.caption) + "</b><div>" + HtmlEncode(item.value) + "</div></li>");

        ul.append(li);
      }

      // Get Size and Position of parent element
      var pos = parentElement.offset(), x = pos.left, y = parentElement.outerHeight();
      mElement.css("left", x);
      mElement.css("margin-top", y);
      //window.alert(parentElement.outerWidth());

      // Show
      mElement.show();

      // Buttons
      var btnCancel = $("<button class='is-button small cross'>Cancel</button>");
      var btnAccept = $("<button class='is-button small tick'>Accept</button>");
      mElement.append(btnCancel);
      mElement.append(btnAccept);

      btnCancel.click(function () {
        // Hide
        Hide();

        // Notify
        if (mOptions.onCancel) mOptions.onCancel(_self, {});
      });

      btnAccept.click(function () {
        // Hide
        Hide();

        // Notify
        if (mOptions.onAccept) {
          // Build a list of all selected items to update
          // NOTE: Currently there is no concept of selecting items so just return an array of all ids
          var ids = [];
          for (var i = 0; i < list.length; i++) {
            var item = list[i];
            if (item.id) ids.push(item.id);
          }

          mOptions.onAccept(_self, { ids: ids });
        }
      });

    }

    // ------------
    // PUBLIC: Hide
    // ------------
    function Hide() {
      if (mElement) mElement.hide();
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "PromptUpdateList",

      Hide: Hide,
      Show: Show,
    };
    return _self;
  }



  // ====================
  // PUBLIC: Label object
  // ====================
  function Label(e, options) {

    var mDropdownPanel;
    var mElement;
    var mElementRow;
    var mOptions;

    // Extend options with defaults
    LabelDefaults = {
      style: "Heading",
      text: null,
      isHtml: false,
      readOnly: false,
      tooltipText: "",
      tooltipHtml: "",
      visible: true,

      onClick: null,
    };
    mOptions = $.extend({}, LabelDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.Label: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Get text
    if (mOptions.text === null) {
      var s = mElement.html();
      if (s && s.indexOf("<") != -1) {
        mOptions.text = mElement.html();
        mOptions.isHtml = true;
      }
      else {
        mOptions.text = mElement.text();
      }
    }

    // Dropdown panel (for tooltip)
    mDropdownPanel = new DropdownPanel(mElement, { cssClass: "is-tooltip" });

    // Initialise
    UpdateElement();

    // Handle Events
    mElement.bind("click", function (e) {
      if (mOptions.tooltipHtml || mOptions.tooltipText) {
        if (mDropdownPanel.Visible()) {
          TooltipHide();
        }
        else {
          TooltipShow();
        }
      }

      // Notify
      if (mOptions.onClick) {
        mOptions.onClick(_self, {});
      }
    });



    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Caption
      if (mOptions.isHtml) {
        mElement.html(mOptions.text);
      }
      else {
        mElement.html(widget.UI.HtmlEncode(mOptions.text));
      }

      // CSS Classes
      var topmost = mElement.hasClass("topmost");
      mElement.removeClass();
      if (topmost) mElement.addClass("topmost");
      switch (mOptions.style.toUpperCase()) {
        case "HEADING":
          mElement.addClass("is-label-heading");
          break;
        case "HYPERLINK":
          mElement.addClass("is-label-hyperlink");
          break;
        case "INFORMATION":
          mElement.addClass("is-label-information");
          break;
        case "NORMAL":
          mElement.addClass("is-label-normal");
          break;
        case "PAGEHEADING":
          mElement.addClass("is-label-pageheading");
          break;
        case "WARNING":
          mElement.addClass("is-label-warning");
          break;
        default:
          console.warn("userinterface.Label: style '" + mOptions.style + "' not supported.");
          break;
      }
      if (mOptions.tooltipHtml || mOptions.tooltipText) {
        mElement.addClass("is-tooltip");
      }
      else {
        mElement.removeClass("is-tooltip");
      }

      // Read-only
      if (mOptions.readOnly) {
      }
      else {
      }

      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }

      // Other
    }

    // ---------------------
    // PUBLIC: Style property
    // ---------------------
    function Style(value) {
      if (value === undefined) {
        // Get
        return mOptions.style;
      }
      else {
        // Set
        mOptions.style = value;

        // Update Element
        UpdateElement();
      }
    }

    // ----------------------------
    // PUBLIC: TooltipHtml property
    // ----------------------------
    function TooltipHtml(value) {
      if (value === undefined) {
        // Get
        return mOptions.tooltipHtml;
      }
      else {
        // Set
        mOptions.tooltipHtml = value;

        // Update Element
        UpdateElement();
      }
    }

    // ----------------------------
    // PUBLIC: TooltipText property
    // ----------------------------
    function TooltipText(value) {
      if (value === undefined) {
        // Get
        return mOptions.tooltipText;
      }
      else {
        // Set
        mOptions.tooltipText = value;

        // Update Element
        UpdateElement();
      }
    }

    // ---------------------
    // PUBLIC: Html property
    // ---------------------
    function Html(value) {
      if (value === undefined) {
        // Get
        return mOptions.text;
      }
      else {
        // Set
        mOptions.text = value;
        mOptions.isHtml = true;

        // Update Element
        UpdateElement();
      }
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return mOptions.text;
      }
      else {
        // Set
        mOptions.text = value;
        mOptions.isHtml = false;

        // Update Element
        UpdateElement();
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Label Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // ----------------------------
    // PUBLIC: Read-Only property
    // ----------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // --------------------------
    // PUBLIC: Hide Tooltip popup
    // --------------------------
    function TooltipHide() {
      mDropdownPanel.Hide();
    }

    // --------------------------
    // PUBLIC: Show Tooltip popup
    // --------------------------
    function TooltipShow() {
      mDropdownPanel.Clear();
      if (mOptions.tooltipHtml) {
        // HTML tooltip
        mDropdownPanel.Append("<span>" + mOptions.tooltipHtml + "</span>");
      }
      else {
        // Plain text tooltip
        mDropdownPanel.Append("<span>" + widget.UI.HtmlEncode(mOptions.tooltipText) + "</span>");
      }
      mDropdownPanel.AttachedControl(_self);
      mDropdownPanel.Show();
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    return {
      TypeName: "Label",

      Element: Element,
      Html: Html,
      ReadOnly: ReadOnly,
      Text: Text,

      TooltipHtml: TooltipHtml,
      TooltipText: TooltipText,
      TooltipHide: TooltipHide,
      TooltipShow: TooltipShow,

      Style: Style,

      Visible: Visible,
      VisibleRow: VisibleRow,
    };
  }



  // ==========================
  // PUBLIC: RangeSlider object
  // ==========================
  function RangeSlider(e, options) {
    var mElement;
    var mElementRow;
    var mLabelElement;
    var mOptions;
    var mValue = 0;
    var mValueOriginal = 0;
    var mWrapperElement;

    // Extend options with defaults
    RangeSliderDefaults = {
      caption: "",

      step: 10,
      minValue: 0,
      maxValue: 100,

      readOnly: false,
      visible: true,

      width: "auto",
      height: "auto",

      trackColour: "",
      trackHeight: "",
      thumbColour: "",
      thumbSize: "",
      thumbStyle: "",

      onChange: null,
    };
    mOptions = $.extend({}, RangeSliderDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");

      // Assign an auto-generated id?
      if (!id) {
        id = "rng" + CreateGuid(true);
        $(e).attr("id", id);
      }
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.RangeSlider: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);
    if ((mElement.attr("type") + "").toUpperCase() != "RANGE") {
      console.warn("widget_ui.RangeSlider: Element '" + id + "' does not have a type attribute of 'range'.");
    };

    // Flag as created
    mElement.attr("is-created", "y");

    // Wrap element
    mElement.wrap("<span class='is-rangeslider' controltype='rangeslider'/>");
    mWrapperElement = $(mElement.parent());

    // Mobile browers don't focus this control when clicked (J033093)
    if (mIsSmallMobileBrowser) {
      mElement[0].addEventListener("touchstart", function () { // Chrome
        mElement.focus();
      });
    }

    // Create label
    mLabelElement = $("<label for='" + id + "'>" + HtmlEncode(mOptions.caption) + "</label>").insertAfter(mElement);

    // Custom styling
    // NOTE: Supported mainly for custom styling in public Portals
    if (mOptions.trackColour || mOptions.trackHeight || mOptions.thumbColour || mOptions.thumbSize || mOptions.thumbStyle) {
      var pf = "input#" + id + ".is-rangeslider[type=range]";
      var th = 20, tw = 39;

      var style = "<style type='text/css'>";

      if (mOptions.trackColour) {
        style += pf + "::-webkit-slider-runnable-track { background-color:" + mOptions.trackColour + "; }";
        style += pf + "::-moz-range-track { background-color:" + mOptions.trackColour + "; }";
        style += pf + "::-ms-fill-lower { background-color:" + mOptions.trackColour + "; }";
        style += pf + "::-ms-fill-upper { background-color:" + mOptions.trackColour + "; }";
      }

      if (mOptions.trackHeight) {
        style += pf + "::-webkit-slider-runnable-track { height:" + mOptions.trackHeight + "px; }";
        style += pf + "::-webkit-slider-runnable-track { margin-top:-12px; }";
        //style += pf + "::-webkit-slider-thumb { margin-top:-" + mOptions.trackHeight + "; }";
        style += pf + "::-webkit-slider-thumb { margin-top:-" + (11 - mOptions.trackHeight / 2) + "px; }";
        style += pf + "::-moz-range-track { height:" + mOptions.trackHeight + "px; }";
        style += pf + "::-ms-fill-lower { height:" + mOptions.trackHeight + "px; }";
        style += pf + "::-ms-fill-upper { height:" + mOptions.trackHeight + "px; }";
      }

      if (mOptions.thumbColour) {
        style += pf + "::-webkit-slider-thumb { background-color:" + mOptions.thumbColour + "; }";
        style += pf + "::-moz-range-thumb { background-color:" + mOptions.thumbColour + "; }";
        style += pf + "::-ms-thumb { background-color:" + mOptions.thumbColour + "; }";
      }

      if (mOptions.thumbStyle) {
        switch (mOptions.thumbStyle.toUpperCase()) {
          case "":
          case "NORMAL":
            break;

          case "CIRCLE":
            tw = th;
            if (!mOptions.thumbSize) mOptions.thumbSize = 1;
            break;

          case "SQUARE":
            tw = th;
            if (!mOptions.thumbSize) mOptions.thumbSize = 1;
            break;
        }
      }

      if (mOptions.thumbSize) {
        style += pf + " { height:" + (th * mOptions.thumbSize) + "px; }";
        style += pf + "::-webkit-slider-thumb { height:" + (th * mOptions.thumbSize) + "px; width:" + (tw * mOptions.thumbSize) + "px; }";
        style += pf + "::-moz-range-thumb { height:" + (th * mOptions.thumbSize) + "px; width:" + (tw * mOptions.thumbSize) + "px; }";
        style += pf + "::-ms-thumb { height:" + (th * mOptions.thumbSize) + "px; width:" + (tw * mOptions.thumbSize) + "px; }";

        switch (mOptions.thumbStyle.toUpperCase()) {
          case "CIRCLE":
            style += pf + "::-webkit-slider-thumb { border-radius:99px }";
            style += pf + "::-moz-range-thumb { border-radius:99px }";
            style += pf + "::-ms-thumb { border-radius:99px }";
            style += pf + "::-moz-range-thumb { height:" + (th * mOptions.thumbSize) + "px; width:" + (tw * mOptions.thumbSize) + "px; }";
            style += pf + "::-ms-thumb { height:" + (th * mOptions.thumbSize) + "px; width:" + (tw * mOptions.thumbSize) + "px; }";
            break;
        }

      }

      style += "</style>";
      mWrapperElement.append(style);
    }

    // Initialise
    UpdateElement();

    // Resize now
    if (mOptions.width != "auto") WidthResizeFromParent();

    // Handle Events
    // NOTE: Different browsers handle change differently so, to get a continuous change event when moving the slider, we must handle both
    //mElement.bind("change", function () {
    mElement.on("change input", function () {
      mValue = mElement.val();
      NotifyChange();
    });


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Class
      mElement.addClass("is-rangeslider");

      // Control
      mElement.attr("min", mOptions.minValue);
      mElement.attr("max", mOptions.maxValue);
      mElement.attr("step", mOptions.step);

      // Read-only
      // NOTE: Checkboxes do not natively support read-only hence we use the disabled attribute instead
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("disabled", "disabled");
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("disabled");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }
    }

    // --------------------------------------
    // PUBLIC: Add a CSS Class to the element
    // --------------------------------------
    function AddClass(className) {
      mWrapperElement.addClass(className);
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
    }

    // -------------------------------------
    // PUBLIC: Get the Thumb Width in pixels
    // -------------------------------------
    function GetThumbWidth() {
      return 39;
    }

    // -------------------------------
    // PUBLIC: Get the Width in pixels
    // -------------------------------
    function GetWidth() {
      return mWrapperElement.width();
    }

    // --------------------------------------------------------------------
    // PUBLIC: Position a jQuery Element at the Thumb's horizontal location
    // --------------------------------------------------------------------
    function PositionElementAtThumb(e, offsetX) {
      if (!offsetX) offsetX = 0;
      var totalWidth = GetWidth() - GetThumbWidth();
      var totalRange = MaxValue() - MinValue();
      e.css("left", (((totalWidth / totalRange) * (Value() - MinValue())) + offsetX) + "px");
    }

    // --------------------
    // Raise OnChange event
    // --------------------
    function NotifyChange() {
      if (mOptions.readOnly) return;

      // Notify
      var e = {};
      if (mOptions.onChange) mOptions.onChange(_self, e);
    }

    // ----------------------------
    // PUBLIC: Read-Only property
    // ----------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        return mValue;
      }
      else {
        // Set
        if (value === null) {
          mValue = 0;
        }
        else {
          mValue = value;
        }
        mElement.val(mValue);
        mValueOriginal = mValue;
      }
    }

    // -------------------------
    // PUBLIC: MaxValue property
    // -------------------------
    function MaxValue(value) {
      if (value === undefined) {
        // Get
        return mOptions.maxValue;
      }
      else {
        // Set
        mOptions.maxValue = value;

        // Refresh
        UpdateElement();
      }
    }

    // -------------------------
    // PUBLIC: MinValue property
    // -------------------------
    function MinValue(value) {
      if (value === undefined) {
        // Get
        return mOptions.minValue;
      }
      else {
        // Set
        mOptions.minValue = value;

        // Refresh
        UpdateElement();
      }
    }

    // ---------------------
    // PUBLIC: Step property
    // ---------------------
    function Step(value) {
      if (value === undefined) {
        // Get
        return mOptions.step;
      }
      else {
        // Set
        mOptions.step = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.RangeSlider.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      mWrapperElement.hide();
      mWrapperElement.show();
      var width = mOptions.width;

      if (fullWidth) {
        width = "100%";
      }
      else {
        if (mOptions.width.toUpperCase() == "AUTO") {
          width = "100%";
        }
        else {
          width = mOptions.width;
        }
      }
      mWrapperElement.css({ width: "100%", "max-width": width });
      mElement.css({ width: "100%", "max-width": width });
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "RangeSlider",

      AddClass: AddClass,
      Caption: Caption,
      Element: Element,
      Focus: Focus,
      GetThumbWidth: GetThumbWidth,
      GetWidth: GetWidth,
      MaxValue: MaxValue,
      MinValue: MinValue,
      PositionElementAtThumb: PositionElementAtThumb,
      ReadOnly: ReadOnly,
      Step: Step,
      Value: Value,
      Visible: Visible,
      VisibleRow: VisibleRow,
      WidthResizeFromParent: WidthResizeFromParent,
    };
    return _self;
  }



  // =======================
  // PUBLIC: Repeater object
  // =======================
  function Repeater(e, options) {

    var mActions = new ActionsCollection();
    var mActiveDataRowListIndex = -1;
    var mButtonsElement;
    var mElement;
    var mOptions;
    var mNewRowCount;
    var mTemplateElementHtml;
    var mVirtualClass;
    var mVirtualData;

    // Extend options with defaults
    RepeaterDefaults = {
      showRowSelectors: true,
      visible: true,

      onAction: null,
      onAfterRowActivate: null,
      onInitialiseRow: null,
      onRowAdd: null,
    };
    mOptions = $.extend({}, RepeaterDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");

      // Assign an auto-generated id?
      if (!id) {
        id = "rpt" + CreateGuid(true);
        $(e).attr("id", id);
      }
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.Repeater: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Allow focus (i.e., so we can handle key presses etc)
    mElement.attr("tabindex", "-1");

    // Get Template Element and remove from DOM
    var te = $("template", mElement);
    if (te.length == 0) {
      console.warn("widget_ui.Repeater: <template> element not found.");
      return;
    }
    else {
      mTemplateElementHtml = te.html();
      te.remove();
    }

    // Flag as created
    mElement.attr("is-created", "y");

    mElement.bind("keydown", function (e) {
      switch (e.keyCode) {
        case 27: // Escape
          ActiveDataRowListIndex(-1);
          mElement.focus();
          widget.UI.ClearTextSelection();
          break;

        //case 38: // Cursor Up

        //case 40: // Cursor Down
      }
    });

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Classes
      mElement.addClass("is-repeater");

      // Create buttons element (for button strip below repeater)
      if (!mButtonsElement) {
        mButtonsElement = $("<div class='is-grid-buttons'></div>");
        mElement.append(mButtonsElement);
      }

      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }
    }

    // ------------------------------------
    // PUBLIC: Refresh the repeater buttons
    // ------------------------------------
    function RefreshButtons() {
      var bl, button, e;
      var hasActionsList = false;
      var hasButtons = false;
      var hasRowActions = false;
      
      // Just in case!
      if (!mButtonsElement) return;

      // Clear existing
      mButtonsElement.children().remove();

      // Add buttons list
      bl = $("<ul></ul>");
      mButtonsElement.append(bl);
      bl.addClass("group"); // Always appear grouped (this just looks better with round buttons)

      // Create a button for each Action
      var firstActionInGroup = null, hasGroups = false;
      for (var i = 0; i < mActions.Actions().length; i++) {
        // Initialise
        var action = mActions.Actions()[i];

        if (!action.actionId) {
          // Separator
          if (firstActionInGroup) {
            hasGroups = true;
            firstActionInGroup = null;

            // Flag last lot of buttons as being grouped
            bl.addClass("group");

            // New group
            bl = $("<ul></ul>");
            bl.addClass("group");
            mButtonsElement.append(bl);
          }
        }
        else if (action.visible) {
          // Track
          hasButtons = true;

          // Add button
          e = $("<li><button class='is-button'></button></li>");
          bl.append(e);
          button = $("button", e);

          // Track
          if (!firstActionInGroup) firstActionInGroup = e;
          hasButtons = true;

          // Update
          if (action.caption) button.text(action.caption);
          if (action.tooltipText) button.attr("title", action.tooltipText);
          if (!action.enabled) button.attr("disabled", "disabled");
          if (action.icon) {
            var iconUrl = widget.GetIconUrl(action.icon, 16);
            if (iconUrl) {
              iconUrl = iconUrl.replace(/\\/g, "/");  // Backslash to forward slash when running from local file system
              button.css({ backgroundImage: "url(" + iconUrl + ")" });
            }
            button.addClass("icon");
          }
          if (action.checked) button.addClass("checked");

          if (action.buttonStyle) {
            button.addClass(action.buttonStyle);
          }
          else {
            // Automatic styles
            // NOTE: Not applicable to HTML Widgets
            switch (action.actionId.toUpperCase()) {
              //case "ADD":
              //  button.addClass("positive");
              //  break;

              //case "REFRESH":
              //  button.addClass("refresh");
              //  e.addClass("system"); // Float to the left
              //  button.attr("title", "Refresh");
              //  break;

              default:
                button.addClass("normal");
                break;
            }
          }

          // Handler
          (function (action) { button.click(function () { ExecuteAction(action.actionId); }); })(action);
        }
        else {
          // Separator
          if (firstActionInGroup) {
            hasGroups = true;
            firstActionInGroup = null;

            // Flag last lot of buttons as being grouped
            bl.addClass("group");

            // New group
            bl = $("<ul></ul>");
            bl.addClass("group");
            mButtonsElement.append(bl);
          }
        }
      }

      // Show/ hide Button Strip
      if (hasButtons) {
        mButtonsElement.show();
      }
      else {
        mButtonsElement.hide();
      }
    }

    // --------------------------
    // PUBLIC: Actions collection
    // --------------------------
    function Actions() {
      return mActions;
    }

    // -------------------------
    // PUBLIC: Execute an Action
    // -------------------------
    function ExecuteAction(actionId) {
      if (mOptions.onAction) {
        mOptions.onAction(_self, actionId);
      }
      else {
        window.alert("widget.UI.Repeater.ExecuteAction: No OnAction defined for this Repeater object.");
      }
    }

    // -------------------------------
    // PUBLIC: Activate First Data Row
    // -------------------------------
    function ActivateFirstDataRow(onlyActivateIfNoActiveDataRow) {
      // Skip?
      if (mActiveDataRowIndex != -1 && onlyActivateIfNoActiveDataRow) return;

      // Activate
      if (mVirtualClass) {
        var index = -1;

        for (var i = 0; i < mVirtualClass.length; i--) {
          if (mVirtualClass[i]) {
            index = i;
            break;
          }
        }

        if (index != -1) ActiveDataRowIndex(index);
      }
    }

    // ------------------------------
    // PUBLIC: Activate Last Data Row
    // ------------------------------
    function ActivateLastDataRow(onlyActivateIfNoActiveDataRow) {
      // Skip?
      if (mActiveDataRowIndex != -1 && onlyActivateIfNoActiveDataRow) return;

      // Activate
      if (mVirtualClass) {
        var index = -1;

        for (var i = mVirtualClass.length - 1; i >= 0; i--) {
          if (mVirtualClass[i]) {
            index = i;
            break;
          }
        }

        if (index != -1) ActiveDataRowIndex(index);
      }
    }

    // ---------------------------------------
    // PUBLIC: ActiveDataRowListIndex property
    // ---------------------------------------
    function ActiveDataRowListIndex(value, holdEvents) {
      if (value === undefined) {
        // Get
        return mActiveDataRowListIndex;
      }
      else {
        // Set
        lastActiveDataRowListIndex = mActiveDataRowListIndex;
        mActiveDataRowListIndex = -1;

        // Clear active row
        $("*", mElement).removeClass("is-sel");

        // Set active row
        for (var i = 0; i < mVirtualData.length; i++) {
          if (mVirtualData[i].listIndex == value) {
            mActiveDataRowListIndex = value;
            mVirtualData[i].itemElement.addClass("is-sel");
            break;
          }
        }

        // Notify
        if (mOptions.onAfterRowActivate && mActiveDataRowListIndex != lastActiveDataRowListIndex) {
          var e = { row: { listIndex: mActiveDataRowListIndex } };
          mOptions.onAfterRowActivate(_self, e);
        }
      }
    }

    // --------------------------
    // PUBLIC: The jQuery Element
    // --------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      //TODO:
      //mElement.focus();
    }
    
    // ----------------------------
    // PUBLIC: Virtual Data Refresh
    // ----------------------------
    function VirtualDataRefresh(virtualClass, retainActiveDataRowIndex) {
      // Set Virtual Data (if supplied)
      if (virtualClass) {
        mVirtualClass = virtualClass;
      }
      mVirtualData = [];

      // Validate
      if (!mOptions.onInitialiseRow) {
        window.alert("widet.UI.Repeater: options.onInitialiseRow handler not specified.");
        return;
      }

      // Clear existing
      mElement.children().remove();
      mButtonsElement = null;
      UpdateElement();

      // Allow virtual binding (ignore items in virtual class that have been deleted, i.e., flagged as null rather than removed from the collection)
      try {
        for (var i = 0; i < mVirtualClass.length; i++) {
          if (mVirtualClass[i] != null) {
            // Create row object for data binding
            var row = CreateRowObject(i);

            // Create event object
            var e = { row: row, repeater: _self };

            // Add to virtual data
            mVirtualData.push(row);

            // Refresh row
            RefreshRow_Internal(i, i);
          }
        }
      }
      catch (ex) {
        window.alert("widget.UI.Repeater.VirtualDataRefresh: " + ex.message);
      }

      // Force Active Data Row List Index to change and therefore fire the event
      mActiveDataRowListIndex = -2;
      ActiveDataRowListIndex(-1);

      // Refresh buttons
      RefreshButtons();
    }

    // ---------------------------------------------------
    // PUBLIC: Refresh a row with the specified list index
    // ---------------------------------------------------
    function RefreshRow(listIndex, index) {
      // Locate Index from List Index
      if (index === undefined) {
        for (var i = 0; i < mVirtualData.length; i++) {
          if (mVirtualData[i].listIndex == listIndex) {
            index = i;
            break;
          }
        }
      }

      // Remove HTML content
      // TODO:

      RefreshRow_Internal(listIndex, index);
    }

    function RefreshRow_Internal(listIndex, index) {
      // Create event object
      var e = { row: mVirtualData[index] };

      // Re-fetch data
      mOptions.onInitialiseRow(_self, e);
    }

    // ---------------------------------------------------------------------
    // PRIVATE: Create a Row Object (required for behind the scenes binding)
    // ---------------------------------------------------------------------
    function CreateRowObject(listIndex) {
      //// Are we dealing with a tr or tbody?
      //window.alert(mTemplateElementHtml);
      //var n1 = mTemplateElementHtml.indexOf("<tr");
      //if (n1 == -1) n1 = mTemplateElementHtml.indexOf("<tbody");
      //var n2 = mTemplateElementHtml.indexOf("<");
      //if (n1 != -1 && n1 == n2) {
      //  window.alert("table row");
      //}

      // Create Item Element and insert
      var item = "<div class='is-repeater-item' listindex='" + listIndex + "'>";
      if (mOptions.showRowSelectors) {
        item += "<div class='row-selector'></div>";
      }
      item += "<div class='content'>" + mTemplateElementHtml + "</div>";
      item += "</div>";
      var itemElement = $(item);
      mElement.append(itemElement);

      // Create row data and set row defaults
      var row = {
        listIndex: listIndex,
        itemElement: itemElement,
        controls: {},
      };

      // Add getting jQuery Element from 'templateid' attribute
      row.GetElement = function (templateid) { return GetElement(row, templateid); };

      // Handle events
      itemElement.on("focusin", function () {
        // Activate row
        var li = parseInt(itemElement.attr("listindex"));
        ActiveDataRowListIndex(li);
      });

      if (mOptions.showRowSelectors) {
        $(".row-selector", itemElement).click(function () {
          // Activate row
          var li = parseInt(itemElement.attr("listindex"));
          ActiveDataRowListIndex(li);

          // Focus first
          FocusFirst(itemElement);
        });
      }

      return row;
    }

    function GetElement(row, templateid) {
      var el = $("*[templateid='" + templateid + "']", row.itemElement);
      if (el.length == 0) {
        window.alert("widget.UI.Repeater.InitialiseRow: No element exists in the template with a templateid of '" + templateid + "'.");
      }
      return el;
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------
    // PUBLIC: Get the Virtual Class that this Repeater is bound to
    // ------------------------------------------------------------
    function GetVirtualClass() {
      return mVirtualClass;
    }

    // ------------------------------------------------------------
    // PUBLIC: Move active row up in the Repeater and Virtual Class
    // ------------------------------------------------------------
    function RowMoveUp() {
      // Within range?
      if (mActiveDataRowListIndex < 1 || mActiveDataRowListIndex >= mVirtualClass.length) return;

      // Swap Rows
      var row1 = mVirtualData[mActiveDataRowListIndex];
      var row2 = mVirtualData[mActiveDataRowListIndex - 1];
      mVirtualData[mActiveDataRowListIndex] = row2;
      mVirtualData[mActiveDataRowListIndex - 1] = row1;
      row1.listIndex -= 1;
      row1.itemElement.attr("listindex", row1.listIndex);
      row2.listIndex += 1;
      row2.itemElement.attr("listindex", row2.listIndex);

      // Swap elements
      row2.itemElement.before(row1.itemElement);

      // Swap entries in Virtual Class
      var item = mVirtualClass[mActiveDataRowListIndex];
      mVirtualClass[mActiveDataRowListIndex] = mVirtualClass[mActiveDataRowListIndex - 1];
      mVirtualClass[mActiveDataRowListIndex - 1] = item;

      // Decrement Active Row
      ActiveDataRowListIndex(mActiveDataRowListIndex - 1);

      // Update Buttons
      RefreshButtons();
    }

    // --------------------------------------------------------------
    // PUBLIC: Move active row down in the Repeater and Virtual Class
    // --------------------------------------------------------------
    function RowMoveDown() {
      // Within range?
      if (mActiveDataRowListIndex < 0 || mActiveDataRowListIndex >= mVirtualClass.length - 1) return;

      // Swap Rows
      var row1 = mVirtualData[mActiveDataRowListIndex];
      var row2 = mVirtualData[mActiveDataRowListIndex + 1];
      mVirtualData[mActiveDataRowListIndex] = row2;
      mVirtualData[mActiveDataRowListIndex + 1] = row1;
      row1.listIndex += 1;
      row1.itemElement.attr("listindex", row1.listIndex);
      row2.listIndex -= 1;
      row2.itemElement.attr("listindex", row2.listIndex);

      // Swap elements
      row1.itemElement.before(row2.itemElement);

      // Swap entries in Virtual Class
      var item = mVirtualClass[mActiveDataRowListIndex];
      mVirtualClass[mActiveDataRowListIndex] = mVirtualClass[mActiveDataRowListIndex + 1];
      mVirtualClass[mActiveDataRowListIndex + 1] = item;

      // Increment Active Row
      ActiveDataRowListIndex(mActiveDataRowListIndex + 1);

      // Update Buttons
      RefreshButtons();
    }

    // -----------------------------------------------------------------------
    // PUBLIC: Remove a repeater row AND the item in the underlying collection
    // -----------------------------------------------------------------------
    function RemoveRowAndCollectionItem(listIndex) {
      if (listIndex < 0 || listIndex > mVirtualClass.length - 1) {
        console.warn("widget_ui.Repeater.RemoveRowAndCollectionItem: listIndex is outside of the bounds of the virtual class.");
        return false;
      }

      // Remove row
      var dre = mVirtualData[listIndex];
      dre.itemElement.remove();
      widget.ArrayRemove(mVirtualData, mVirtualData[listIndex]);

      // Remove from collection
      widget.ArrayRemove(mVirtualClass, mVirtualClass[listIndex]);

      // Update Row Counts and list indexes
      for (var i = 0; i < mVirtualData.length; i++) {
        var dr = mVirtualData[i];
        dr.listIndex = i;
        dr.itemElement.attr("listIndex", i);
      }

      // Update Active Row
      if (mActiveDataRowListIndex != -1 && listIndex <= mActiveDataRowListIndex) {
        var i = mActiveDataRowListIndex;
        if (i < 0) i = 0;
        if (i > mVirtualData.length - 1) i = mVirtualData.length - 1;
        ActiveDataRowListIndex(i);
      }

      return true;
    }

    // ---------------------
    // PUBLIC: Add a new Row
    // ---------------------
    function AddRow(activateNewRow) {
      // Max rows already added?
      //if (mNewRowCount >= mOptions.maxNewRows) return false;

      // Increment count
      mNewRowCount += 1;

      // Notify
      if (mOptions.onRowAdd) {
        // Record original collection size
        var count = mVirtualClass.length;

        // Create event object
        var e = { cancel: false };

        // Call
        mOptions.onRowAdd(_self, e);

        // Cancelled?
        if (e.cancel) return false;

        // Add row
        if (mVirtualClass.length <= count) {
          window.alert("Repeater's onRowAdd handler did not add a new item to the collection this repeater is bound to.");
          return false;
        }
        else if (mVirtualClass.length != count + 1) {
          window.alert("Repeater's onRowAdd handler added multiple rows to the collection this repeater is bound to. It should only add a single item.");
          return false;
        }

        // Create row object for data binding
        var index = mVirtualClass.length - 1;
        var row = CreateRowObject(index);

        // Create event object
        var e = { row: row, repeater: _self };

        // Add to virtual data
        mVirtualData.push(row);

        // Refresh row
        RefreshRow_Internal(index, index);

        // Activate
        if (activateNewRow) {
          ActiveDataRowListIndex(index);

          // Focus first
          FocusFirst(mVirtualData[index].itemElement);
        }
       }
     else {
        window.alert("Repeater does not handle onRowAdd.");
        return false;
      }

      return true;
    }



    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "Repeater",

      ActivateLastDataRow: ActivateLastDataRow,
      ActivateFirstDataRow: ActivateFirstDataRow,
      ActiveDataRowListIndex: ActiveDataRowListIndex,
      AddRow: AddRow,
      Element: Element,
      Focus: Focus,
      GetVirtualClass: GetVirtualClass,
      RefreshButtons: RefreshButtons,
      RefreshRow: RefreshRow,
      RemoveRowAndCollectionItem: RemoveRowAndCollectionItem,

      Actions: Actions,

      RowMoveUp: RowMoveUp,
      RowMoveDown: RowMoveDown,

      VirtualDataRefresh: VirtualDataRefresh,
      Visible: Visible,
    };

    // Associate this control to HTML input element (for container validation)
    mElement.prop("is-control", _self);

    return _self;
  }



  // ===================
  // PUBLIC: Tabs object
  // ===================
  function Tabs(e, options) {

    var mBookmarked = false;
    var mBookmarkElement;
    var mBookmarkVisible = true;
    var mElement;
    var mHeadingElement;
    var mSummaryElement;
    var mOptions;
    var mSelectedTabId = "";
    var mLastSelectedTabId = "";
    var mLastSelectedTabIndex = -1;
    var mSelectedTabIndex = -1;
    var mTabs;
    var mTabsElement;

    // Extend options with defaults
    TabDefaults = {
      cssClass: "is-tabs",
      pagesParent: null,
      style: "normal",
      pageTransition: "", // slide, fade
      visible: true,

      showBookmark: false,
      bookmarkEnabled: false,

      onBookmarkClick: null,
      onSelectedTabChanged: null,
    };
    mOptions = $.extend({}, TabDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      e = $("#" + e);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      widget.RegisterError("widget_ui.Tabs: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Get Pages Parent (only required if dynamically adding Tabs and Pages)
    if (mOptions.pagesParent) {
      if (typeof mOptions.pagesParent == "string") {
        mOptions.pagesParent = $("#" + mOptions.pagesParent);
      }
    }

    // Remove whitespace (e.g., line breaks) between LI elements to avoid spacing issues
    $("ul,li", mElement).contents().filter(function () {
      return this.nodeType = Node.TEXT_NODE && /\S/.test(this.nodeValue) == false;
    }).remove();

    // Get/ Create Tabs Element
    mTabsElement = $("ul", mElement);
    if (mTabsElement.length == 0) {
      mTabsElement = $("<ul></ul>");
      mElement.append(mTabsElement);
    }

    // Get Tabs and associated pages
    mTabs = [];
    var tabEls = $("li", mTabsElement);
    for (var i = 0; i < tabEls.length; i++) {
      var tabEl = $(tabEls[i]);
      var tab = { tabId: tabEl.attr("tabId"), element: tabEl, caption: tabEl.text(), visible: true, tooltipText: tabEl.attr("tooltipText") };

      // Find related page
      var page = $("div#page" + tab.tabId);
      if (page.length != 0) {
        tab.pageElement = page;
        tab.pageElement.addClass("is-tab-page");
      }

      // Handle events
      tabEl.click(function () {
        var tabId = $(this).attr("tabId");
        if (tabId != mSelectedTabId) {
          // Change Tabs
          SelectedTabId(tabId, true);

          // Notify
          if (mOptions.onSelectedTabChanged) mOptions.onSelectedTabChanged();
        }
      });

      // Warnings
      if (!tab.tabId) {
        widget.RegisterError("widget_ui.Tabs: Tab '" + tab.caption + "' does not have a 'tabId' attribute to identify it.");
      }
      if (!tab.pageElement) {
        widget.RegisterError("widget_ui.Tabs: Tab '" + tab.tabId + "' does not have an associated page element (a div element with an id of 'page" + tab.tabId + "').");
      }

      mTabs.push(tab);
    }

    // Initialise
    UpdateElement();

    // Select first visible Tab
    for (var i = 0; i < mTabs.length; i++) {
      if (mTabs[i].visible) {
        SelectedTabIndex(i);
        break;
      }
    }


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Classes
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);
      mElement.addClass("is-no-select");

      // Style
      switch (mOptions.style.toUpperCase()) {
        case "CUSTOM":
          mElement.show();
          break;

        case "NORMAL":
          mElement.show();
          break;

        case "WIZARD":
          mElement.hide();
          break;

        default:
          widget.RegisterError("widget_ui.Tabs: Invalid style '" + mOptions.style + "'. Must be either: Normal, Wizard, Custom");
      }

      // Bookmark
      if (mBookmarkElement) {
        // Bookmarked?
        if (mBookmarked) {
          mBookmarkElement.attr("bookmarked", "true");
        }
        else {
          mBookmarkElement.removeAttr("bookmarked");
        }

        // Visible?
        if (mBookmarkVisible) {
          mBookmarkElement.show();
        }
        else {
          mBookmarkElement.hide();
        }
      }

      // Visibility
      UpdateVisibility();
    }

    // -------------------
    // Create Tab Elements
    // -------------------
    function CreateTabElements() {
      var hiddenCount = 0;

      // Remove existing elements
      mTabsElement.children().remove();

      // Add tab elements
      for (var i = 0; i < mTabs.length; i++) {
        var tab = mTabs[i];

        // Add tab
        var e = $("<li class='is-selectable'></li>");
        mTabsElement.append(e);

        // Save element
        tab.element = e;

        // Tab properties
        if (tab.cssClass) e.addClass(tab.cssClass);

        // Icon and Caption
        var html = "";
        if (tab.symbol) {
          html = "<div class='is-symbol is-symbol-" + tab.symbol.toLowerCase() + "' title='" + HtmlEncode(tab.caption) + "'></div>";
        }
        else {
          html = HtmlEncode(tab.caption);
        }
        //if (t.icon) {
        //  var iconUrl = GetIconUrl(t.icon, 16);
        //  html = "<img src='" + iconUrl + "'/>" + html;
        //}
        e.html(html);

        // Hidden?
        if (tab.hidden) hiddenCount += 1;

        // Handle Tab click and context menu events
        (function (tabId) {
          e.click(function () {
            // Initialise
            var t = GetTabById(tabId);

            // Select Tab
            // NOTE: Certain forms such as Tasks rely on detecting a second Tab click
            var sameTab = (tabId == mSelectedTabId);
            SelectedTabId(tabId, true);
            if (sameTab) {
              t.pageElement.removeClass("hold-animation");
            }

            // Notify
            if (mOptions.onSelectedTabChanged) mOptions.onSelectedTabChanged();
          });
        })(tab.tabId);
        //if (mOptions.pageShortcutForm) {
        //  (function (tabId) {
        //    $UI.HandleContextMenuEvent($("a", e), function (e) {
        //      ShowContextMenu(tabId, e);
        //      e.preventDefault();
        //      return false;
        //    });
        //  })(mTabs[i].tabId);
        //}
      }

      // Special Toggle-Hidden Tab
      //if (hiddenCount) {
      //  var e = $("<li class='toggle-hidden'><a>&nbsp;</a></li>");
      //  mTabsElement.append(e);
      //  e.click(function () {
      //    mTabsElement.toggleClass("hidden-visible");
      //  });
      //}

      // Update styles
      UpdateTabStyles();
    }

    // ------------------------------
    // PRIVATE: Update Tab Styles etc
    // ------------------------------
    function UpdateTabStyles(userAction) {
      // Determine Selected Tab Index (required here for page transitions)
      for (var i = 0; i < mTabs.length; i++) {
        if (mTabs[i].tabId == mSelectedTabId) mSelectedTabIndex = i;
      }

      // Update Tab selected style and pages visibility
      for (var i = 0; i < mTabs.length; i++) {
        var tab = mTabs[i];

        if (tab.visible) tab.element.show(); else tab.element.hide();

        // If using page transitions, ensure container has a special class
        if (mOptions.pageTransition && tab.pageElement) {
          tab.pageElement.addClass(mOptions.pageTransition);
          tab.pageElement.parent().addClass("is-tabs-page-transition-container");

          switch (mOptions.pageTransition) {
            case "slide":
              tab.pageElement.removeClass("slide-in-from-right slide-in-from-left slide-out-to-left slide-out-to-right");
              break;

            default:
              console.warn("widget.UI.Tabs: Unsupported page transition '" + mOptions.pageTransition + "'");
          }
        }

        if (tab.tabId == mSelectedTabId) {
          tab.element.addClass("selected");

          if (tab.pageElement) {
            tab.pageElement.show();

            // Page Transition
            switch (mOptions.pageTransition) {
              case "":
                break;

              case "slide":
                // Slide in from left or right
                if (userAction) {
                  if (mSelectedTabIndex > mLastSelectedTabIndex) {
                    tab.pageElement.addClass("slide-in-from-right");
                  }
                  else {
                    tab.pageElement.addClass("slide-in-from-left");
                  }
                }
                break;

              default:
                console.warn("widget.UI.Tabs: Unsupported page transition '" + mOptions.pageTransition + "'");
            }
          }
        }
        else {
          tab.element.removeClass("selected");

          if (tab.pageElement) {
            if (mOptions.pageTransition && tab.tabId == mLastSelectedTabId) {
              // Page Transition (all transitions take 500ms)
              switch (mOptions.pageTransition) {
                case "slide":
                  // Slide out to left or right
                  if (userAction) {
                    if (mSelectedTabIndex > mLastSelectedTabIndex) {
                      tab.pageElement.addClass("slide-out-to-left");
                    }
                    else {
                      tab.pageElement.addClass("slide-out-to-right");
                    }
                    (function (tab) {
                      var ti = window.setTimeout(function () {
                        window.clearTimeout(ti);
                        ti = null;

                        if (tab.tabId != mSelectedTabId) tab.pageElement.hide();
                      }, 500);
                    })(tab);
                  }
                  break;

                default:
                  console.warn("widget.UI.Tabs: Unsupported page transition '" + mOptions.pageTransition + "'");
                  tab.pageElement.hide();
              }
            }
            else {
              tab.pageElement.hide();
            }
          }
        }
      }

      // Auto Format
      AutoFormatPage();

      // Add bookmark element and handle click event
      // NOTE: J030923 this is done in a different place from FINCC since CreateTabElements isn't generally called for widgets!
      if (mOptions.showBookmark) {
        // Create element
        if (!mBookmarkElement) {
          mBookmarkElement = $("<li class='bookmark'><a>&nbsp;</a></li>");
          mTabsElement.append(mBookmarkElement);

          mBookmarkElement.on("click", function () {
            if (mOptions.onBookmarkClick) {
              mOptions.onBookmarkClick();
            }
            else {
              window.alert("widget.UI.Tabs control does not specify an onBookmarkClick event handler.");
            }
          });
        }

        // Update
        if (mOptions.bookmarkEnabled) {
          mBookmarkElement.attr("title", "Toggle Bookmark");
          mBookmarkElement.removeClass("disabled");
        }
        else {
          mBookmarkElement.addClass("disabled");
          mBookmarkElement.attr("title", "");
        }
      }

      // Finalise
      mLastSelectedTabId = mSelectedTabId;
      mLastSelectedTabIndex = mSelectedTabIndex;
    }

    // ----------------------
    // PUBLIC: AutoFormatPage
    // ----------------------
    function AutoFormatPage() {
      // Get Selected Tab
      var selectedTab = mTabs[mSelectedTabIndex];

      // Automatic tidy-up of section labels (so hidden labels to not produce a large top gap)
      if (selectedTab && selectedTab.pageElement && !selectedTab.pageElement.hasClass("no-auto-format")) {
        var els = $("label.is-label-heading", selectedTab.pageElement);
        els.removeClass("topmost");

        // Apply class to label in first visible table row
        for (var i = 0; i < els.length; i++) {
          var el = $(els[i]);
          var t = el.closest("table");
          var tb = el.closest("tbody");
          var tr = el.closest("tr");

          if (t.css("display") != "none" && tb.css("display") != "none" && tr.css("display") != "none") {
            // Found
            el.addClass("topmost");
            //el.css("border", "4px solid pink");
            break;
          }
        }
      }
    }

    // ------------------------------
    // PRIVATE: Update the Visibility
    // ------------------------------
    function UpdateVisibility() {
      var CountVisible = 0;

      // Pages
      for (var i = 0; i < mTabs.length; i++) {
        var tab = mTabs[i];

        if (mOptions.visible && tab.visible) {
          tab.element.show();
          CountVisible += 1;
        }
        else {
          tab.element.hide();
          if (tab.pageElement) tab.pageElement.hide();
        }
      }

      // Tabs
      if (!mOptions.visible) {
        mElement.hide();
      }
    }

    // ------------------------------
    // PUBLIC: The jQuery DIV Element
    // ------------------------------
    function Element() {
      return mElement;
    }

    // -----------------------------------------------------------------------------------------------------------
    // PUBLIC: Focus on the first Input field on the selected Tab page (not, by default on mobile browsers though)
    // -----------------------------------------------------------------------------------------------------------
    function FocusFirst(forceEvenIfMobileBrowser) {
      if (Runtime_IsMobileBrowser) {
        if (!forceEvenIfMobileBrowser) return;
      }

      // Get input controls on the current Tab page
      if (mSelectedTabIndex != -1) {
        var ctrls = $("input,select,textarea,div[tabindex=-1],span[tabindex=0]", mTabs[mSelectedTabIndex].pageElement);

        // Exclude disabled, read-only and invisible elements
        for (var i = 0; i < ctrls.length; i++) {
          var c = $(ctrls[i]);
          var include = true;

          if (include && c.prop("disabled")) include = false;
          if (include && c.is("[readonly]")) {
            if (c.hasClass("fetchingdata")) {
              // Ignore since this is a DBCombo that is only read-only because it is fetching data!
            }
            else {
              include = false;
            }
          }
          if (include && !c.is(":visible")) {
            if (c.attr("type") == "checkbox") {
              // Checkboxes are always hidden so we must look at the actual control's label
              var chkid = c.prop("id");
              var chklbl = $("label[for='" + chkid + "']");
              if (chklbl.length == 1 && !chklbl.is(":visible")) {
                include = false;
              }
            }
            else {
              include = false;
            }
          }

          if (include) {
            c.focus().select();
            break;
          }
        }
      }
    }

    // ------------------------------
    // PUBLIC: Return a Tab by Tab Id
    // ------------------------------
    function GetTabById(tabId) {
      return Tabs(tabId);
    }

    // -----------------------------
    // PUBLIC: Return a Tab by index
    // -----------------------------
    function GetTabByIndex(index) {
      return mTabs[index];
    }

    // -----------------------------
    // PRIVATE: Return specified tab
    // -----------------------------
    function Tabs(tabId) {
      tabId = tabId.toUpperCase();
      for (var i = 0; i < mTabs.length; i++) {
        if (mTabs[i].tabId.toUpperCase() == tabId) return mTabs[i];
      }

      return null;
    }

    // --------------------------
    // PUBLIC: Get TabId by Index
    // --------------------------
    function GetTabIdByIndex(index) {
      if (index < 0 || index >= mTabs.length) {
        return "";
      }
      else {
        return mTabs[index].tabId;
      }
    }

    // ---------------------------
    // PUBLIC: Get Tab Index by Id
    // ---------------------------
    function GetTabIndexById(id) {
      for (var i = 0; i < mTabs.length; i++) {
        if (mTabs[i].tabId == id) {
          return i;
        }
      }

      return -1;
    }

    // ----------------------------------------
    // PUBLIC: Get Selected Page jQuery Element
    // ----------------------------------------
    function GetSelectedPageElement() {
      if (mSelectedTabIndex < 0 || mSelectedTabIndex >= mTabs.length) {
        return null;
      }
      else {
        return mTabs[mSelectedTabIndex].pageElement;
      }
    }

    // -------------------------------------
    // PUBLIC: Refresh from an array of Tabs
    // -------------------------------------
    function RefreshFromArray(tabs) {
      mTabs = [];
      mSelectedTabId = "";
      mSelectedTabIndex = -1;

      if (tabs) {
        for (var i = 0; i < tabs.length; i++) {
          TabsAdd(tabs[i].tabId, tabs[i], true);
        }
      }

      CreateTabElements();
    }

    // ----------------------------------
    // PUBLIC: Selected First Visible Tab
    // ----------------------------------
    function SelectFirstVisibleTab() {
      mSelectedTabId = "";
      mSelectedTabIndex = -1;

      for (var i = 0; i < mTabs.length; i++) {
        if (mTabs[i].visible) {
          SelectedTabId(mTabs[i].tabId);
          break;
        }
      }
    }

    // ------------------------------
    // PUBLIC: SelectedTabId property
    // ------------------------------
    function SelectedTabId(value, selectedByUser) {
      if (value === undefined) {
        // Get
        return mSelectedTabId;
      }
      else {
        // Set
        if (value != mSelectedTabId) {
          mSelectedTabId = value;

          // Hide/ Show Tabs and Pages based on visibility and select correct tab
          mSelectedTabIndex = -1;
          UpdateTabStyles(selectedByUser);
        }
        else {
          // Auto-Format page, even if not changed (e.g., single page wizards)
          AutoFormatPage();
        }
      }
    }

    // ---------------------------------
    // PUBLIC: SelectedTabIndex property
    // ---------------------------------
    function SelectedTabIndex(value) {
      if (value === undefined) {
        // Get
        return mSelectedTabIndex;
      }
      else {
        // Set
        if (value < 0 || value >= mTabs.length) {
          SelectedTabId("");
          widget.RegisterError("widget_ui.Tabs: SelectTabByIndex failed. Index must be between 0 and " + (mTabs.length - 1) + ".");

        }
        else {
          SelectedTabId(mTabs[value].tabId);
        }
      }
    }

    // ---------------------------------------------
    // PUBLIC: Show a single Tab and hide all others
    // ---------------------------------------------
    function ShowSingleTab(tabId) {
      mSelectedTabId = tabId;
      tabId = tabId.toUpperCase();

      // Hide All
      for (var i = 0; i < mTabs.length; i++) {
        var tab = mTabs[i];

        tab.visible = (tabId == tab.tabId.toUpperCase());
      }
      UpdateVisibility();
      UpdateTabStyles();
    }

    // ---------------------
    // PUBLIC: Show all Tabs
    // ---------------------
    function ShowAllTabs() {
      // Show All
      for (var i = 0; i < mTabs.length; i++) {
        var tab = mTabs[i];

        tab.visible = true;
      }
      UpdateVisibility();
      UpdateTabStyles();
    }

    // ----------------------
    // PUBLIC: Style property
    // ----------------------
    function Style(value) {
      if (value === undefined) {
        // Get
        return mOptions.style;
      }
      else {
        // Set
        if (value != mOptions.style) {
          mOptions.style = value;
          UpdateElement();
        }
      }
    }

    // ---------------------------
    // PUBLIC: TabCaption property
    // ---------------------------
    function TabCaption(tabId, caption) {
      // Get Tab
      var tab = Tabs(tabId);

      if (tab == null) {
        console.warn("TabCaption: Cannot find tab '" + tabId + "'.");
      }

      if (caption == undefined) {
        // Get
        return tab.caption;
      }
      else {
        // Set
        tab.caption = caption;
        tab.element.text(caption);
      }
    }

    // -------------------------------
    // PUBLIC: TabTooltipText property
    // -------------------------------
    function TabTooltipText(tabId, tooltipText) {
      // Get Tab
      var tab = Tabs(tabId);

      if (tab === null) {
        console.warn("TabTooltipText: Cannot find tab '" + tabId + "'.");
      }

      if (tooltipText === undefined) {
        // Get
        return tab.tooltipText;
      }
      else {
        // Set
        tab.tooltipText = tooltipText;
        tab.element.attr("title", tooltipText);
      }
    }

    // ----------------------------
    // PUBLIC: Tab Visible property
    // ----------------------------
    function TabVisible(tabId, visible) {
      // Get Tab
      var tab = Tabs(tabId);

      if (tab === null) {
        console.warn("TabVisible: Cannot find tab '" + tabId + "'.");
      }

      if (visible === undefined) {
        // Get
        return tab.visible;
      }
      else {
        // Set
        tab.visible = visible;
        UpdateElement();
      }
    }

    // --------------------------------
    // PUBLIC: TabVisibleIndex property
    // --------------------------------
    function TabVisibleIndex(index, visible) {
      // Get Tab
      var tab = mTabs[index];

      if (tab === null) {
        console.warn("TabVisibleIndex: Cannot find tab " + index + ".");
      }

      if (visible === undefined) {
        // Get
        return tab.visible;
      }
      else {
        // Set
        tab.visible = visible;
        UpdateElement();
      }
    }

    // ------------------------------------
    // PUBLIC: LastVisibleTabIndex property
    // ------------------------------------
    function LastVisibleTabIndex() {
      var last = -1;

      for (var i = 0; i < mTabs.length; i++) {
        if (mTabs[i].visible) last = i;
      }
      return last;
    }

    // -------------------------
    // PUBLIC: TabCount property
    // -------------------------
    function TabCount() {
      return mTabs.length;
    }

    // ----------------------------------
    // PUBLIC: Visible Tab Count property
    // ----------------------------------
    function TabCountVisible() {
      var count = 0;

      for (var i = 0; i < mTabs.length; i++) {
        if (mTabs[i].visible) count += 1;
      }

      return count;
    }

    // -----------------------------
    // PUBLIC: Dynamically add a Tab
    // -----------------------------
    function TabsAdd(tabId, options, holdUpdate) {
      options = $.extend({}, { caption: "", cssClass: null, pageElement: null, visible: true }, options);

      // Create tab
      var t = { tabId: tabId };
      var e = $("<li></li>");
      mTabsElement.append(e);

      // Tab properties
      t.caption = options.caption || tabId;
      t.cssClass = options.cssClass;
      t.pageElement = options.pageElement;
      t.symbol = options.symbol;
      t.visible = options.visible;

      // Create Page Element?
      if (!t.pageElement) {
        if (mOptions.pagesParent) {
          t.pageElement = $("<div class='is-tab-page'></div>");
          mOptions.pagesParent.append(t.pageElement);
        }
        else {
          window.alert("Tabs cannot automatically create Page element since no pagesParent element was specified in the creation options for this Tabs control.");
        }
      }
      //t.bulletText = Page.BulletText;

      // Add to collection
      mTabs.push(t);

      // Select first tab by default
      if (!mSelectedTabId) {
        mSelectedTabId = t.tabId;
        mSelectedTabIndex = mTabs.length - 1;
      }

      // Create Tabs
      if (holdUpdate) {
        // Deferred
      }
      else {
        CreateTabElements();
      }

      // Return Tab
      return t;
    }

    // ----------------
    // PUBLIC: Validate
    // ----------------
    function Validate(currentPageOnly, allControls) {
      if (currentPageOnly) {
        var t = Tabs(mSelectedTabId);
        if (t) {
          return ValidateContainer(t.pageElement, undefined, undefined, allControls);
        }
        else {
          window.alert("Tabs.Validate: No current tab.");
          return false;
        }
      }
      else {
        for (var i = 0; i < mTabs.length; i++) {
          if (!mTabs[i].visible) {
            // Tab hidden, e.g., due to licence or configuration settings
          }
          else {
            if (!ValidateContainer(mTabs[i].pageElement, _self, i, allControls)) {
              return false;
            }
          }
        }

        return true;
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ---------------------------
    // PUBLIC: Bookmarked property
    // ---------------------------
    function Bookmarked(value) {
      if (value == undefined) {
        // Get
        return mBookmarked;
      }
      else {
        // Set
        mBookmarked = value;

        // Update element
        UpdateElement();
        UpdateTabStyles();
      }
    }

    // ---------------------------------
    // PUBLIC: Bookmark Visible property
    // ---------------------------------
    function BookmarkVisible(value) {
      if (value == undefined) {
        // Get
        return mBookmarkVisible;
      }
      else {
        // Set
        mBookmarkVisible = value;

        // Update element
        UpdateElement();
        UpdateTabStyles();
      }
    }

    // ---------------------------------
    // PUBLIC: Bookmark Enabled property
    // ---------------------------------
    function BookmarkEnabled(value) {
      if (value == undefined) {
        // Get
        return mOptions.bookmarkEnabled;
      }
      else {
        // Set
        mOptions.bookmarkEnabled = value;

        // Update element
        UpdateElement();
        UpdateTabStyles();
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "Tabs",

      Bookmarked: Bookmarked,
      BookmarkEnabled: BookmarkEnabled,
      BookmarkVisible: BookmarkVisible,

      Element: Element,

      AutoFormatPage: AutoFormatPage,
      FocusFirst: FocusFirst,

      GetTabById: GetTabById,
      GetTabByIndex: GetTabByIndex,
      GetTabIdByIndex: GetTabIdByIndex,
      GetTabIndexById: GetTabIndexById,
      GetSelectedPageElement: GetSelectedPageElement,
      Tabs: Tabs,

      RefreshFromArray: RefreshFromArray,

      Style: Style,

      SelectFirstVisibleTab: SelectFirstVisibleTab,
      SelectedTabId: SelectedTabId,
      SelectedTabIndex: SelectedTabIndex,
      ShowSingleTab: ShowSingleTab,
      ShowAllTabs: ShowAllTabs,

      TabCount: TabCount,
      TabCountVisible: TabCountVisible,
      TabCaption: TabCaption,
      TabTooltipText: TabTooltipText,
      TabVisible: TabVisible,
      TabVisibleIndex: TabVisibleIndex,
      TabsAdd: TabsAdd,
      LastVisibleTabIndex: LastVisibleTabIndex,

      Validate: Validate,
      Visible: Visible,
    };
    return _self;
  }


  // ======================
  // PUBLIC: TextBox object
  // ======================
  function TextBox(e, options) {

    var mActionsButtonElement;
    var mAddressLookupInitialised = false;
    var mBaseScrollHeight;
    var mButtonStrip;
    var mDataTypeValidationData;
    var mDataTypeValidationElement;
    var mDataTypeIsValid = true;
    var mElement;
    var mElementRow;
    var mFocused = false;
    var mIsValid = true;
    var mLabelElement;
    var mPromptUpdateList;
    var mOptions;
    var mTagsList = [];
    var mTagsListElement;
    var mTagsListElementParent;
    var mTagsTimer;
    var mTextOriginal = "";
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;
    var mWrapperElement;

    // Extend options with defaults
    TextBoxDefaults = {
      captionElement: "auto",
      cssClass: "is-textbox",

      allowBlank: true,
      autoTab: false,
      blankTip: "",

      maxLength: 0,
      multiLine: false,
      minHeight: "32px",
      spellCheck: null,

      readOnly: false,
      autoReadOnly: true,

      visible: true,

      width: "auto",
      widthButtonsInclusive: true,
      rows: 1,
      autoExpand: false,
      autoExpandMaxRows: null,

      password: false,
      passwordRevealOnFocus: false, // NOTE: To be used mainly by admin forms where a password/ token is stored as part of the record

      onChange: null,
      onButtonClick: null,
      onEnterKey: null,

      changeWhileTyping: false,

      hyperlinkContent: false,
      onContentHyperlink: null,
      onFocus: null,

      tagsListElement: null,

      specialType: null,

      dataType: "",           // addresslookup, companynumber, email, phone, taxnumberindividual, taxnumberorganisation
      dataTypeReformat: null, // E.g., if dataType is "phone" then reformat value if necessary, null indicates a prompt will be given

      actionsButtonIcon: null,
      actionsButtonVisible: false,
      onActionsButtonClick: null,
    };
    mOptions = $.extend({}, TextBoxDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.TextBox: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Default spellCheck if not supplied
    if (mOptions.spellCheck === null) {
      mOptions.spellCheck = mOptions.multiLine ? true : false;
    }

    // Auto-populate Blank Tip?
    if (!mOptions.blankTip) {
      mOptions.blankTip = mElement.attr("placeholder");
    }

    // Replace control?
    if (mOptions.multiLine) {
      // Replace with textarea if multi-line
      // NOTE: Preserve classes for external libraries such as: Material Design Lite
      var classes = mElement.attr("class");
      var textarea = $("<textarea id='" + mElement.attr("id") + "' style='resize:none'></textarea>");
      mElement.replaceWith(textarea);
      mElement = textarea;
      if (mOptions.rows) mElement.attr("rows", mOptions.rows);
      if (classes) mElement.addClass(classes);
    }

    // Wrap element
    var parentDockFill = false;
    if (!mDisableControlStyling) {
      // Respect parent dock fill
      parentDockFill = mElement.parent().hasClass("is-dock-fill");

      mElement.wrap("<span style='white-space:normal; padding:0; margin:0; flex-direction:row' controltype='textbox'/>");
      mElement.css("flex-grow", "1");
    }
    mWrapperElement = $(mElement.parent());
    if (parentDockFill) mWrapperElement.addClass("is-dock-fill");

    // Password?
    if (mOptions.password) {
      if (mOptions.passwordRevealOnFocus) {
        mElement.attr("autocomplete", "new-password");

        // J032062 (prevent Chrome from revealing passwords - if they're not actually password fields, it won't try!)
        mElement.css("text-security", "disc");
        mElement.css("-webkit-text-security", "disc");
      }
      else {
        mElement.attr("type", "password");
      }
    }

    // Actions button element
    // NOTE: This is different to the button strip that can appear after the control
    mActionsButtonElement = $("<button class='is-control-actions-button' type='button'></button>");
    if (mOptions.actionsButtonIcon) {
      var iconUrl = widget.GetIconUrl(mOptions.actionsButtonIcon, 16);
      mActionsButtonElement.addClass("icon");
      mActionsButtonElement.append("<img src='" + iconUrl + "'/>");
    }
    mWrapperElement.append(mActionsButtonElement);
    mActionsButtonElement.click(function () {
      if (mOptions.actionsButtonVisible) {
        if (mOptions.onActionsButtonClick) {
          mOptions.onActionsButtonClick(_self);
        }
        else {
          window.alert("onActionsButtonClick is not handled!");
        }
      }
    });

    // Validation elements
    mDataTypeValidationElement = $("<label style='display:none; align-items:center; padding-left:4px;'></label>");
    mWrapperElement.append(mDataTypeValidationElement);
    mValidationElement = $("<label style='display:none' class='is-validation-tip'></label>");
    mWrapperElement.append(mValidationElement);

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Calculate width if 'auto'
    if (mOptions.width == "auto" && mOptions.maxLength != 0) {
      WidthResizeFromParent();
    }

    // Handle events
    mElement.blur(function () {
      if (Changed()) {
        NotifyChange();
        DataTypeValidate(mOptions.dataTypeReformat);
      }
      mTextOriginal = mElement.val();

      mFocused = false;

      // Hide password?
      if (mOptions.password && mOptions.passwordRevealOnFocus) {
        // J032062 (prevent Chrome from revealing passwords - if they're not actually password fields, it won't try!)
        mElement.css("text-security", "disc");
        mElement.css("-webkit-text-security", "disc");
      }

      //// Hide tags list?
      //TagsListHide();
    });
    mElement.focus(function () {
      mFocused = true;

      // Reveal password?
      if (mOptions.password && mOptions.passwordRevealOnFocus) {
        // J032062 (prevent Chrome from revealing passwords - if they're not actually password fields, it won't try!)
        mElement.css("text-security", "");
        mElement.css("-webkit-text-security", "");
      }

      // Data Type
      switch (mOptions.dataType.toUpperCase()) {
        case "ADDRESSLOOKUP":
          // Address Lookup
          if (!mAddressLookupInitialised && !mOptions.readOnly) {
            mAddressLookupInitialised = true;

            mElement.attr("autocomplete", "");

            // Attach address lookup
            widget.UI.InitialiseAddressAutoComplete({
              streetAddress: _self
            });
          }
          else if (mAddressLookupInitialised && mOptions.readOnly) {
            // Disable address lookup
            mElement.attr("autocomplete", "off");
          }
          break;
      }

      // Track focused element for Tags List
      if (mTagsListElement) mTagsListElement.prop("tlt", mElement);

      // Notify
      if (mOptions.onFocus) {
        mOptions.onFocus(_self, {});
      }
    });
    if (mOptions.changeWhileTyping) {
      var events = "keyup paste";
      var t = mElement.attr("type");
      if (t && t.toLowerCase() == "search") {
        // On search boxes, clicking the cross to clear the control fires the input event
        events += " input";
      }
      mElement.on(events, function () {
        NotifyChange();  // Do not check Changed()

        if (mTextOriginal != mElement.val()) {
          console.warn("widget_ui.TextBox: changeWhileTyping is enabled but no onChange handler is setting e.changeHandled to true. Ignore if by design but this may mean code is called multiple times needlessly.");
        }
      });
    }
    if (mOptions.multiLine && mOptions.autoExpand) {
      mElement.on("input", AutoExpand);
    }
    if (mOptions.autoTab) {
      mElement.on("input", function (e) {
        if (Text().length >= mOptions.maxLength) {
          e.preventDefault();
          $("input,select,textarea")[$("input,select,textarea").index(this) + 1].focus();


        }
      });
    }
    if (mOptions.onEnterKey) {
      mElement.on("keydown", function (e) {
        if (e.keyCode == 13) mOptions.onEnterKey();
      });
    }
    if (mOptions.onContentHyperlink) {
      mElement.on("click", function () {
        if (mOptions.readOnly && mOptions.hyperlinkContent && mOptions.onContentHyperlink) {
          mOptions.onContentHyperlink();
        }
      });
    }
    mDataTypeValidationElement.click(function () { Focus(); });
    mValidationElement.click(function () { Focus(); });

    // Enter key moves to next field (finPOWER Connect desktop only)?
    if (widget.Options.enterMovesToNextField && !mOptions.onEnterKey && !mOptions.multiLine) {
      mElement.on("keyup", function (e) {
        if (e.keyCode == 13) TriggerTab($(this));
      });
    }

    // Other
    mTagsListElement = mOptions.tagsListElement;

    // Special Type
    if (mOptions.specialType) {
      switch (mOptions.specialType.toUpperCase()) {
        case "SEARCH":
          // Search
          mWrapperElement.addClass("is-textbox-special-search");
          var btnSearch = $("<button class='search' title='Search'></button>");
          mWrapperElement.append(btnSearch);
          btnSearch.on("click", function () {
            mElement.focus();
            if (mOptions.onEnterKey) mOptions.onEnterKey();
          });
          break;
      }
    }

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // CSS Classes
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);
      if (mOptions.multiLine && !mOptions.autoExpand) {
        mElement.css({ minHeight: mOptions.minHeight });
      }
      else {
        mElement.css({ minHeight: "" });
      }
      if (mLabelElement && mLabelElement.parent().prop("tagName") == "TH") {
        if (mOptions.multiLine) {
          mLabelElement && mLabelElement.parent().addClass("top");
        }
        else {
          mLabelElement && mLabelElement.parent().removeClass("top");
        }
      }

      // Sizing related
      if (mOptions.maxLength == 0 || mOptions.maxLength > 100) {
        if (mOptions.width && mOptions.width != "auto") {
          mWrapperElement.css("display", "inline-flex");
        }
        else {
          mWrapperElement.css("display", "flex");
        }
      }
      else {
        //mWrapperElement.css("display", "inline");
        mWrapperElement.css("display", "inline-flex");
      }

      // Allow Blank
      if (mOptions.allowBlank) {
        mElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }
      mElement.attr("placeholder", mOptions.blankTip);

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("readonly");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Hyperlink Content (only when read-only)
      if (mOptions.hyperlinkContent) {
        mElement.addClass("is-hyperlink");
        mElement.addClass("is-hyperlink");
      }
      else {
        mElement.removeClass("is-hyperlink");
      }

      // Other
      mElement.attr("maxLength", mOptions.maxLength == 0 ? "" : mOptions.maxLength);
      if (mOptions.width != "auto") mElement.css({ width: mOptions.width });
      if (mOptions.spellCheck && !mOptions.password) {
        mElement.attr("spellcheck", "true");
      }
      else {
        mElement.attr("spellcheck", "false");
      }
      if (mOptions.multiLine && mOptions.rows) {
        if (mOptions.autoExpand) {
          if (!mBaseScrollHeight) mBaseScrollHeight = mElement[0].scrollHeight;
          AutoExpand();
        }
        else {
          mElement.attr("rows", mOptions.rows);
        }
      }

      // Actions button
      if (mOptions.actionsButtonVisible) {
        mWrapperElement.addClass("is-control-actions-button");
        mActionsButtonElement.show();
      }
      else {
        mWrapperElement.removeClass("is-control-actions-button");
        mActionsButtonElement.hide();
      }

      // Data type validation message
      // NOTE: Data type validation is for informational purposes only and should not be confused with the IsValid property
      if (mOptions.dataType && !mOptions.readOnly) {
        if (mDataTypeIsValid) {
          mElement.removeClass("is-data-invalid");
          mDataTypeValidationElement.hide();
        }
        else {
          mElement.addClass("is-data-invalid");
          mDataTypeValidationElement.css("display", "inline-flex");
        }
      }
      else {
        mElement.removeClass("is-data-invalid");
        mDataTypeValidationElement.hide();
      }

      // Validation message
      if (mIsValid) {
        // Valid
        mElement.removeClass("is-invalid");
        mValidationElement.css({ display: "none" });
      }
      else {
        // Invalid
        mElement.addClass("is-invalid");
        if (mValidationText) {
          mValidationElement.attr("title", "");

          if (mValidationTextIsHtml) {
            mValidationElement.html(mValidationText);
          }
          else {
            mValidationElement.text(mValidationText);
          }
          mValidationElement.css({ display: "flex" });
        }
        else {
          mValidationElement.css({ display: "none" });
        }
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }
    }

    // -------------------------
    // PRIVATE: Auto-Expand Rows
    // -------------------------
    function AutoExpand() {
      if (mOptions.multiLine && mOptions.autoExpand) {
        mElement.css("height", "1px");
        var scrollHeight = mElement[0].scrollHeight;
        var rows = Math.ceil((scrollHeight - mBaseScrollHeight) / 16);
        if (rows < 0) rows = 0;
        if (mOptions.autoExpandMaxRows && rows + mOptions.rows > mOptions.autoExpandMaxRows) rows = mOptions.autoExpandMaxRows - mOptions.rows;
        mElement.attr("rows", mOptions.rows + rows);
        mElement.css("height", "unset");
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // -------------------------
    // PUBLIC: BlankTip property
    // -------------------------
    function BlankTip(value) {
      if (value === undefined) {
        // Get
        return mOptions.blankTip;
      }
      else {
        // Set
        mOptions.blankTip = value;

        // Update element
        UpdateElement();
      }
    }

    // ---------------
    // PU8LIC: Buttons
    // ---------------
    function Buttons() {
      if (!mButtonStrip) {
        // Buttons
        var ebl = $("<div></div>");
        mWrapperElement.append(ebl);
        mButtonStrip = ButtonStrip(ebl, {
          onButtonClick: mOptions.onButtonClick,
          visible: false,
          parentControl: _self,
        });
      }

      return mButtonStrip;
    }

    // ----------------------
    // PUBLIC: Define Buttons
    // ----------------------
    function ButtonsDefine(buttons) {
      // Get Button Strip (created on-demand)
      var bs = Buttons();

      // Define
      if (!buttons) buttons = [];
      bs.ButtonsDefine(buttons);

      // Show
      mButtonStrip.Visible(buttons.length != 0);
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // ---------------------------------------------
    // PUBLIC: Has changed in current edit operation
    // ---------------------------------------------
    function Changed() {
      return mElement.val() != mTextOriginal;
    }

    // --------------------------
    // PUBLIC: Data Type property
    // --------------------------
    function DataType(value) {
      if (value === undefined) {
        // Get
        return mOptions.dataType;
      }
      else {
        // Set
        mOptions.dataType = value;

        // Update element
        UpdateElement();
      }
    }

    // ---------------------------------
    // PUBLIC: DataTypeReformat property
    // ---------------------------------
    function DataTypeReformat(value) {
      if (value === undefined) {
        // Get
        return mOptions.dataTypeReformat;
      }
      else {
        // Set
        mOptions.dataTypeReformat = value;
      }
    }

    // ----------------------------
    // FRIEND: Raise OnChange event
    // ----------------------------
    function NotifyChange() {
      // Notify
      var e = { ChangeHandled: false, TextOriginal: mTextOriginal };
      if (mOptions.onChange) mOptions.onChange(_self, e);

      // Reset TextOriginal?
      if (e.ChangeHandled) mTextOriginal = mElement.val();
    }

    // -------------------------------------------------------------------------
    // PUBLIC: Validate based on dateType option and reformat/ warn if necessary
    // -------------------------------------------------------------------------
    function DataTypeValidate(reformat) {
      // Initialise
      if (mPromptUpdateList) mPromptUpdateList.Hide();
      mDataTypeIsValid = true;
      mDataTypeValidationElement.html("");
      mDataTypeValidationElement.attr("title", "");

      // Validate
      if (mOptions.readOnly || !Text()) {
        // Do not validate
      }
      else {
        switch (mOptions.dataType.toUpperCase()) {
          case "ADDRESSLOOKUP":
            // Address Lookup
            break;

          case "COMPANYNUMBER":
            // Company Number
            DataTypeValidate_CompanyNumber(reformat);
            break;

          case "EMAIL":
            // Email
            DataTypeValidate_Email(reformat);
            break;

          case "PHONE":
            // Phone
            DataTypeValidate_Phone(reformat);
            break;

          case "TAXNUMBERINDIVIDUAL":
            // Tax Number (Individual)
            DataTypeValidate_TaxNumberIndividual(reformat);
            break;
          case "TAXNUMBERORGANISATION":
            // Tax Number (Organisation)
            DataTypeValidate_TaxNumberOrganisation(reformat);
            break;
        }
      }

      // Update
      UpdateElement();
    }

    // -----------------------
    // PRIVATE: Company Number
    // -----------------------
    function DataTypeValidate_CompanyNumber(reformat) {
      widget._SystemGetString("DataType_ValidateCompanyNumber", { value: Text() },
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Invalid?
          if (data.Value == Text()) {
            if (data.Valid) {
              if (mOptions.readOnly) {
                // Ignore
              }
              else {
                // Reformat
                if (reformat === null && data.Value != data.ValueFormatted) {
                  // Prompt (since no reformat parameter was specified)
                  mDataTypeValidationData = data;

                  if (!mPromptUpdateList) {
                    mPromptUpdateList = widget.UI.PromptUpdateList({
                      onAccept: function (sender, e) {
                        // Update
                        for (var i = 0; i < e.ids.length; i++) {
                          switch (e.ids[i]) {
                            case "CompanyNumber":
                              Text(mDataTypeValidationData.ValueFormatted);
                              break;
                          }
                        }
                      }
                    });
                  }

                  // Build update list
                  var list = [];
                  list.push({ id: "CompanyNumber", caption: Caption(), value: data.ValueFormatted });

                  mPromptUpdateList.Show(_self, list);
                }
                else if (reformat) {
                  // Update now
                  Text(data.ValueFormatted);
                }
              }
            }
            else {
              mDataTypeIsValid = false;
              mDataTypeValidationElement.html("<img src='" + widget.GetIconUrl("Control_Number|Warning", 20) + "' style='width:20px; height:20px'/>");
              mDataTypeValidationElement.attr("title", data.Message);              
            }

            // Update
            UpdateElement();
          }
          else {
            // Ignore since value has changed!
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.TextBox.DataTypeValidate: Failed to validate company number: " + data);
          //UpdateElement(false);
        }
      );
    }

    // -------------------------------------------------------
    // PRIVATE: Validate Email (no need for server-side check)
    // -------------------------------------------------------
    function DataTypeValidate_Email(reformat) {
      // No need for server-side check
      if (!/^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/.test(Text())) {
        mDataTypeIsValid = false;
        mDataTypeValidationElement.html("<img src='" + widget.GetIconUrl("Email|Warning", 20) + "' style='width:20px; height:20px'/>");
        mDataTypeValidationElement.attr("title", "Invalid Email.");
      }
    }

    // -----------------------
    // PRIVATE: Validate Phone
    // -----------------------
    function DataTypeValidate_Phone(reformat) {
      widget._SystemGetString("DataType_ValidatePhone", { value: Text() },
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Update?
          if (data.Value == Text()) {
            if (data.Valid) {
              if (mOptions.readOnly) {
                // Ignore
              }
              else {
                // Reformat
                if (reformat === null && data.Value != data.ValueFormatted) {
                  // Prompt (since no reformat parameter was specified)
                  mDataTypeValidationData = data;

                  if (!mPromptUpdateList) {
                    mPromptUpdateList = widget.UI.PromptUpdateList({
                      onAccept: function (sender, e) {
                        // Update
                        for (var i = 0; i < e.ids.length; i++) {
                          switch (e.ids[i]) {
                            case "Phone":
                              Text(mDataTypeValidationData.ValueFormatted);
                              break;
                          }
                        }
                      }
                    });
                  }

                  // Build update list
                  var list = [];
                  list.push({ id: "Phone", caption: Caption(), value: data.ValueFormatted });

                  mPromptUpdateList.Show(_self, list);
                }
                else if (reformat) {
                  // Update now
                  Text(data.ValueFormatted);
                }
              }
            }
            else {
              mDataTypeIsValid = false;
              mDataTypeValidationElement.html("<img src='" + widget.GetIconUrl("Phone_Mobile|Warning", 20) + "' style='width:20px; height:20px'/>");
              mDataTypeValidationElement.attr("title", data.Message);
            }

            // Update
            UpdateElement();
          }
          else {
            // Ignore since value has changed!
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.TextBox.DataTypeValidate: Failed to validate phone: " + data);
          //UpdateElement(false);
        }
      );
    }

    // --------------------------------
    // PRIVATE: Tax Number (Individual)
    // --------------------------------
    function DataTypeValidate_TaxNumberIndividual(reformat) {
      widget._SystemGetString("DataType_ValidateTaxNumberIndividual", { value: Text() },
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Invalid?
          if (data.Value == Text()) {
            if (data.Valid) {
              if (mOptions.readOnly) {
                // Ignore
              }
              else {
                // Reformat
                if (reformat === null && data.Value != data.ValueFormatted) {
                  // Prompt (since no reformat parameter was specified)
                  mDataTypeValidationData = data;

                  if (!mPromptUpdateList) {
                    mPromptUpdateList = widget.UI.PromptUpdateList({
                      onAccept: function (sender, e) {
                        // Update
                        for (var i = 0; i < e.ids.length; i++) {
                          switch (e.ids[i]) {
                            case "TaxNumber":
                              Text(mDataTypeValidationData.ValueFormatted);
                              break;
                          }
                        }
                      }
                    });
                  }

                  // Build update list
                  var list = [];
                  list.push({ id: "TaxNumber", caption: Caption(), value: data.ValueFormatted });

                  mPromptUpdateList.Show(_self, list);
                }
                else if (reformat) {
                  // Update now
                  Text(data.ValueFormatted);
                }
              }
            }
            else {
              mDataTypeIsValid = false;
              mDataTypeValidationElement.html("<img src='" + widget.GetIconUrl("Control_Number|Warning", 20) + "' style='width:20px; height:20px'/>");
              mDataTypeValidationElement.attr("title", data.Message);              
            }

            // Update
            UpdateElement();
          }
          else {
            // Ignore since value has changed!
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.TextBox.DataTypeValidate: Failed to validate individual tax number: " + data);
          //UpdateElement(false);
        }
      );
    }

    // ----------------------------------
    // PRIVATE: Tax Number (Organisation)
    // ----------------------------------
    function DataTypeValidate_TaxNumberOrganisation(reformat) {
      widget._SystemGetString("DataType_ValidateTaxNumberOrganisation", { value: Text() },
        function (data) {
          // Parse
          data = JSON.parse(data);

          // Invalid?
          if (data.Value == Text()) {
            if (data.Valid) {
              if (mOptions.readOnly) {
                // Ignore
              }
              else {
                // Reformat
                if (reformat === null && data.Value != data.ValueFormatted) {
                  // Prompt (since no reformat parameter was specified)
                  mDataTypeValidationData = data;

                  if (!mPromptUpdateList) {
                    mPromptUpdateList = widget.UI.PromptUpdateList({
                      onAccept: function (sender, e) {
                        // Update
                        for (var i = 0; i < e.ids.length; i++) {
                          switch (e.ids[i]) {
                            case "TaxNumber":
                              Text(mDataTypeValidationData.ValueFormatted);
                              break;
                          }
                        }
                      }
                    });
                  }

                  // Build update list
                  var list = [];
                  list.push({ id: "TaxNumber", caption: Caption(), value: data.ValueFormatted });

                  mPromptUpdateList.Show(_self, list);
                }
                else if (reformat) {
                  // Update now
                  Text(data.ValueFormatted);
                }
              }
            }
            else {
              mDataTypeIsValid = false;
              mDataTypeValidationElement.html("<img src='" + widget.GetIconUrl("Control_Number|Warning", 20) + "' style='width:20px; height:20px'/>");
              mDataTypeValidationElement.attr("title", data.Message);              
            }

            // Update
            UpdateElement();
          }
          else {
            // Ignore since value has changed!
          }
        },

        function (data) {
          mWarningMessage = data;
          widget.RegisterError("widget_ui.TextBox.DataTypeValidate: Failed to validate organisation tax number: " + data);
          //UpdateElement(false);
        }
      );
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // ----------------------------------
    // PUBLIC: The jQuery Wrapper Element
    // ----------------------------------
    function WrapperElement() {
      return mWrapperElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      if (!mIsSmallMobileBrowser) mElement.select();
    }

    // ---------------------------------------------------
    // PUBLIC: Hyperlink Content (when read-only) property
    // ---------------------------------------------------
    function HyperlinkContent(value) {
      if (value === undefined) {
        // Get
        return mOptions.hyperlinkContent;
      }
      else {
        // Set
        if (value != mOptions.hyperlinkContent) {
          mOptions.hyperlinkContent = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // --------------------------
    // PUBLIC: MaxLength property
    // --------------------------
    function MaxLength(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.maxLength) {
          mOptions.maxLength = value;

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ---------------------
    // PUBLIC: Text property
    // ---------------------
    function Text(value) {
      if (value === undefined) {
        // Get
        return Runtime_GetString(mElement, true);
      }
      else {
        // Set
        mElement.val(value);
        mTextOriginal = value;

        // Auto-Expand
        AutoExpand();
      }
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function WidthResizeFromParent(fullWidth) {
      var width = mOptions.width;
      var maxWidth = "";

      if (mOptions.maxLength == 0 || mOptions.maxLength > 100 || fullWidth) {
        width = "100%";
      }
      else {
        maxWidth = (mOptions.maxLength * 0.8) + "em";
        width = "100%";
      }
      mWrapperElement.css({ width: width, maxWidth: maxWidth });
      mElement.css({ width: width, maxWidth: maxWidth, "margin-right": 0 });

      // Buttons
      if (mOptions.widthButtonsInclusive && mButtonStrip && mButtonStrip.Visible()) {
        var bsw = mButtonStrip.Element().outerWidth();
        var ew = mElement.css("width");
        mElement.css("width", "calc(" + ew + " - " + bsw + "px)");
      }
    }

    // -----------------------------------------------------
    // PUBLIC: Resize from Parent (for multi-line textboxes)
    // -----------------------------------------------------
    function ResizeFromParent() {
      if (mOptions.multiLine) {
        mWrapperElement.css({ width: "100%", height: "100%", overflow: "visible", display: "inline-block" });
        mElement.css({ width: "100%", height: "100%", overflow: "auto" });
      }
      else {
        // Just resize width
        WidthResizeFromParent();
      }
    }

    // -------------------------------------------------------------------
    // PUBLIC: Define an array of Tags from a Code Description List object
    // -------------------------------------------------------------------
    function TagsListDefineFromCodeDescriptionList(codeDescriptionList) {
      var tagsList = [];

      if (codeDescriptionList) {
        for (var i = 0; i < codeDescriptionList.length; i++) {
          var item = codeDescriptionList[i];
          tagsList.push({ caption: item.Code, value: "[" + item.Code + "]" });
        }
      }

      TagsListDefine(tagsList);
    }

    // -------------------------------------------------------------------------------
    // PUBLIC: Define an array of Tags ({caption: "", value: ""}) to show when focused
    // -------------------------------------------------------------------------------
    function TagsListDefine(tagsList) {
      mTagsList = tagsList;

      // Build HTML element
      if (mTagsList && mTagsList.length != 0) {
        if (mTagsListElement) {
          if (!mTagsListElement.attr("tleid")) mTagsListElement.attr("tleid", CreateGuid(true));
          mTagsListElement.addClass("is-textbox-tagslist");
          mTagsListElement.hide();

          mTagsListElement.children().remove();
        }
        else {
          mTagsListElement = $("<div class='is-textbox-tagslist' style='display:none' tleid='" + CreateGuid(true) + "'></div>");
          
          // We don't support both buttons after and tags
          mWrapperElement.css("flex-direction", "column");
          mElement.css("flex-grow", "1");

          if (mOptions.multiLine) {
            // Below textbox
            mWrapperElement.append(mTagsListElement);
          }
          else {
            // Above textbox
            mWrapperElement.prepend(mTagsListElement);
          }
        }

        mTagsListElementParent = mTagsListElement.parent();

        mElement.attr("tleid", mTagsListElement.attr("tleid"));
        var ul = $("<ul></ul>");
        var lastPrefix = "", lastPrefixIndex = -1;
        var colours = ["#ccf5f3", "#8c6700", "#ffe0e0", "#e4e0fb", "#daf5e8", "#caeefe", "#f8f8f8", "#977c00", "#5f8603"];
        var bgcolours = ["#20b2aa", "#ffd561", "#ff6666", "#7b68ee", "#47ce8e", "#02A8F3", "#bdbdbd", "#ffe87c", "#ccfb5d"];
        for (var i = 0; i < tagsList.length; i++) {
          var tag = mTagsList[i];
          var li = $("<li tabindex='-1'></li>"); // Allow focus to keep things consistent when showing/ hiding Tags List

          // For clarity, it the caption contains a dot (e.g., "Client.Name") then style differently either side
          var n = tag.caption.indexOf(".");
          if (n == -1) {
            li.text(tag.caption);
          }
          else {
            var left = tag.caption.substr(0, n);
            if (left != lastPrefix) {
              lastPrefix = left;
              lastPrefixIndex += 1;
              if (lastPrefixIndex >= colours.length) lastPrefixIndex = 0;
            }
            var right = widget.SplitWordsAtCapitals(tag.caption.substr(n + 1));

            // NOTE: Assign a CSS class just in case someone wants to customise their own colours
            li.html("<span class='is-tag-group-" + lastPrefixIndex + "' style='font-weight:bold; display:inline-block; margin-left:-2px; padding:0 2px 0 2px; border-radius:4px 0 0 4px; color:" + colours[lastPrefixIndex] + "; background-color: " + bgcolours[lastPrefixIndex] + ";'>" + left + "</span>" + "." + "<span>" + right + "</span>");
          }

          li.attr("value", tag.value);
          ul.append(li);
        }
        mTagsListElement.append(ul);

        // Handle events
        $("li", ul).click(
          function () {
            // Get target control (for shared tags lists)
            var e = mTagsListElement.prop("tlt");
            //window.setTimeout(function () { e.focus(); }, 10);
            e.focus();
            TagInsert(e, $(this).attr("value"));
          });

        mTagsListElementParent.focusin(function () {
          if (mTagsTimer) {
            window.clearInterval(mTagsTimer);
            mTagsTimer = null;
          }

          TagsListShow();
        });
        mTagsListElementParent.focusout(function () {
          if (mTagsTimer) {
            window.clearInterval(mTagsTimer);
            mTagsTimer = null;
          }
          mTagsTimer = window.setInterval(function () {
            TagsListHide();
          }, 500);
        });
      }
      else {
        if (!mOptions.tagsListElement) mTagsListElement = null;
      }
    }

    // -----------------------
    // PRIVATE: Show Tags List
    // -----------------------
    function TagsListShow() {
      if (mTagsListElement && !mOptions.readOnly) {
        // Set target control (for shared tags lists)
        mTagsListElement.stop();
        //mTagsListElement.prop("tlt", mElement);

        // Show
        //mTagsListElement.slideDown("fast");
        mTagsListElement.fadeIn("fast");

        //if (mTagsListTimer) {
        //  // Ignore close
        //  window.clearTimeout(mTagsListTimer);
        //  mTagsListTimer = null;
        //}
        //else {
        //  if (mTagsListElement.prop("showing") != true) {
        //    mTagsListElement.slideDown("fast");
        //    mTagsListElement.prop("showing", true);
        //  }
        //}
      }
    }

    // -----------------------
    // PRIVATE: Hide Tags List
    // -----------------------
    function TagsListHide() {
      if (mTagsListElement) {
        mTagsListElement.stop();
        //mTagsListElement.slideUp("fast");
        mTagsListElement.fadeOut("fast");

        //// Mouse down so don't hide!
        //if(mElement.prop("taghold") == true) return;

        //// Delay so clicking tag does not close tags strip
        //if (mTagsListTimer) window.clearTimeout(mTagsListTimer);
        //mTagsListTimer = window.setTimeout(function () {
        //  // It is possible that this tags list element is shared between multiple controls (like Account Banking Details) so ensure that if another of these is focused that we don't hide the tags list
        //  var ae = $(document.activeElement);
        //  if (ae.length != 0) {
        //    if (ae.attr("tleid") == mElement.attr("tleid")) {
        //      // Same group so don't close
        //    }
        //    else {
        //      if (mTagsListElement.prop("showing") == true) {
        //        mTagsListElement.slideUp("fast");
        //        mTagsListElement.prop("showing", false);
        //      }
        //    }
        //    mTagsListTimer = null;
        //  }
        //}, 10);
      }
    }

    // -------------------------
    // PRIVATE: Insert Tag value
    // -------------------------
    function TagInsert(tlt, value) {
      if (!mOptions.readOnly) {
        InsertAtCaret(tlt, value);
      }
    }

    // --------------------------------
    // PUBLIC: Insert text at the caret
    // --------------------------------
    function InsertAtCaret(tlt, text) {
      var e = tlt[0]; //mElement[0];
      var pos = e.selectionStart;
      var len = e.selectionEnd - pos;
      var s = tlt.val();
      tlt.val(s.substring(0, pos) + text + s.substring(pos + len));

      if (len) {
        e.selectionStart = pos;
        e.selectionEnd = pos + text.length;
      }
      else {
        e.selectionStart = pos + text.length;
        e.selectionEnd = pos + text.length;
      }

      // Notify
      NotifyChange();
    }

    // ------------------------
    // PUBLIC: Is control valid
    // ------------------------
    function IsValid() {
      return mIsValid ? true : false;
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      mIsValid = isValid;
      if (validationText === undefined) mValidationText = ""; else mValidationText = validationText;
      if (validationTextIsHtml === undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

      // Update element
      UpdateElement();
    }

    // ---------------------------------------
    // PUBLIC: Actions Button Visible property
    // ---------------------------------------
    function ActionsButtonVisible(value) {
      if (value === undefined) {
        // Get
        return mOptions.actionsButtonVisible;
      }
      else {
        // Set
        if (value != mOptions.actionsButtonVisible) {
          mOptions.actionsButtonVisible = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ------------------------------
    // PUBLIC: Actions Button Element
    // ------------------------------
    function ActionsButtonElement() {
      return mActionsButtonElement;
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.TextBox.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "TextBox",

      //ActionsButtonElement: ActionsButtonElement,
      //ActionsButtonVisible: ActionsButtonVisible,
      AllowBlank: AllowBlank,
      AutoReadOnly: AutoReadOnly,
      BlankTip: BlankTip,
      Buttons: Buttons,
      ButtonsDefine: ButtonsDefine,
      Caption: Caption,
      Changed: Changed,
      DataType: DataType,
      DataTypeReformat: DataTypeReformat,
      DataTypeValidate: DataTypeValidate,
      Element: Element,
      Focus: Focus,
      //HyperlinkContent: HyperlinkContent,
      MaxLength: MaxLength,
      ReadOnly: ReadOnly,
      ResizeFromParent: ResizeFromParent,
      TagsListDefine: TagsListDefine,
      TagsListDefineFromCodeDescriptionList: TagsListDefineFromCodeDescriptionList,
      Text: Text,
      Visible: Visible,
      VisibleRow: VisibleRow,

      WrapperElement: WrapperElement,
      WidthResizeFromParent: WidthResizeFromParent,

      //IsValid: IsValid,
      //ValidationSet: ValidationSet,

      // Friend
      NotifyChange: NotifyChange, // For Parameters Host after Range Lookup
      TextOriginal: function () { return mTextOriginal; },
    };
    return _self;
  }


  // ==============================
  // PUBLIC: RadioButtonList object
  // ==============================
  function RadioButtonList(e, options) {

    var mCheckBoxes = [];
    var mElement;
    var mElementRow;
    var mIsValid = true;
    var mLabelElement;
    var mOptions;
    var mValue = null;
    var mValidationElement;
    var mValidationText = "";
    var mValidationTextIsHtml = false;
    var mWrapperElement;

    // Extend options with defaults
    RadioButtonListDefaults = {
      captionElement: "auto",
      layout: "horizontal",

      allowBlank: true,
      blankValidationMessage: "You must select a value",

      readOnly: false,
      autoReadOnly: true,

      visible: true,
      list: [],

      onChange: null,
    };
    mOptions = $.extend({}, RadioButtonListDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.RadioButtonList: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Wrap element
    mElement.wrap("<span style='padding:0; margin:0;' controltype='radiobuttonlist'/>");
    mWrapperElement = $(mElement.parent());

    // Validation elements
    mValidationElement = $("<label style='display:none' class='is-validation-tip'></label>");
    mWrapperElement.append(mValidationElement);

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Handle events
    mValidationElement.click(function () { Focus(); });

    // Create List
    if (mOptions.list && mOptions.list.length != 0) {
      RecreateList();
    }

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Layout
      mElement.removeClass("horizontal,vertical");
      mElement.addClass(mOptions.layout);

      // Allow Blank
      if (mOptions.allowBlank) {
        mElement.removeClass("is-mandatory");
        if (mLabelElement) mLabelElement.removeClass("is-mandatory");
      }
      else {
        mElement.addClass("is-mandatory");
        if (mLabelElement) mLabelElement.addClass("is-mandatory");
      }

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
        mElement.attr("readonly", "readonly");
      }
      else {
        mElement.removeClass("is-readonly");
        mElement.removeAttr("readonly");
      }
      if (mOptions.autoReadOnly) {
        mElement.attr("autoreadonly", "true");
      }
      else {
        mElement.removeAttr("autoreadonly");
      }

      // Validation message
      if (mIsValid) {
        mValidationElement.css({ display: "none" });
        mElement.removeClass("is-invalid");
      }
      else {
        mElement.addClass("is-invalid");
        if (mValidationText) {
          if (mValidationTextIsHtml) {
            mValidationElement.html(mValidationText);
          }
          else {
            mValidationElement.text(mValidationText);
          }
          mValidationElement.css({ display: "flex" });
        }
        else {
          mValidationElement.css({ display: "none" });
        }
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }
    }

    // ----------------------
    // PRIVATE: Recreate List
    // ----------------------
    function RecreateList() {
      // Clear existing
      for (var i = 0; i < mCheckBoxes.length; i++) {
        var chk = mCheckBoxes[i];
        chk.WrapperElement().remove();
      }
      mCheckBoxes = [];

      // Add checkboxes
      if (mOptions.list) {
        for (i = 0; i < mOptions.list.length; i++) {
          var item = mOptions.list[i];
          var input = $("<input type='checkbox'/>");
          mElement.append(input);
          var chk = RadioButton(input, {
            caption: item.caption,
            visible: item.visible !== false,
            readOnly: item.enabled === false || mOptions.readOnly,

            onChange: function (sender, e) {
              // Set Value
              if (sender.Value()) {
                mValue = sender._TagValue;
              }
              else {
                if (mOptions.allowBlank) {
                  mValue = null;
                }
                else {
                  sender.Value(true);
                  return; // Cannot blank this control
                }
              }

              // Clear validation message
              ValidationSet(true, "", false);

              // Uncheck all others
              for (var i = 0; i < mCheckBoxes.length; i++) {
                var chk2 = mCheckBoxes[i];
                if (chk2 !== sender) chk2.Value(false);
              }

              // Notify
              if (mOptions.onChange) {
                mOptions.onChange(_self, {});
              }
            },
          });

          chk._TagValue = item.value;
          mCheckBoxes.push(chk);
        }
      }
    }

    // --------------------------------------------------------
    // PUBLIC: Set the List from an Array of JavaScript objects
    // --------------------------------------------------------
    function ListFromArray(list) {
      mOptions.list = list;

      // Rebuild List
      var oldValue = Value();
      RecreateList();
      Value(oldValue);
    }

    // ----------------------------------------
    // PUBLIC: Set the Enabled state of an item
    // ----------------------------------------
    function ItemEnabled(value, enabled) {
      var found = false;

      // Initialise
      value = (value + "").toUpperCase();

      for (var i = 0; i < mOptions.list.length; i++) {
        var item = mOptions.list[i];

        if ((item.value + "").toUpperCase() == value) {
          found = true;
          item.enabled = enabled;
          break;
        }
      }

      // Rebuild List
      if (found) {
        var oldValue = Value();
        RecreateList();
        Value(oldValue);
      }
    }

    // ----------------------------------------
    // PUBLIC: Set the Visible state of an item
    // ----------------------------------------
    function ItemVisible(value, visible) {
      var found = false;

      // Initialise
      value = (value + "").toUpperCase();

      for (var i = 0; i < mOptions.list.length; i++) {
        var item = mOptions.list[i];

        if ((item.value + "").toUpperCase() == value) {
          found = true;
          item.visible = visible;
          break;
        }
      }

      // Rebuild List
      if (found) {
        var oldValue = Value();
        RecreateList();
        Value(oldValue);
      }
    }

    // ----------------------------
    // PUBLIC: Allow Blank property
    // ----------------------------
    function AllowBlank(value) {
      if (value != mOptions.allowBlank) {
        mOptions.allowBlank = (value == true);

        // Update element
        UpdateElement();
      }
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      if (mCheckBoxes.length != 0) {
        mCheckBoxes[0].Focus();
      }
    }

    // --------------------------
    // PUBLIC: Read-Only property
    // --------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = (value == true);

          // Recreate List (since this creates read-only checkboxes)
          var oldValue = Value();
          RecreateList();
          Value(oldValue);

          // Update element
          UpdateElement();
        }
      }
    }

    // -------------------------------
    // PUBLIC: Auto Read-Only property
    // -------------------------------
    function AutoReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.autoReadOnly;
      }
      else {
        // Set
        if (value != mOptions.autoReadOnly) {
          mOptions.autoReadOnly = (value == true);

          // Update element
          UpdateElement();
        }
      }
    }

    // ----------------------
    // PUBLIC: Value property
    // ----------------------
    function Value(value) {
      if (value === undefined) {
        // Get
        return mValue;
      }
      else {
        // Set
        mValue = value;

        // Select correct checkbox
        for (var i = 0; i < mCheckBoxes.length; i++) {
          var chk = mCheckBoxes[i];
          chk.Value(chk._TagValue == mValue);
        }

        // Update
        UpdateElement();
      }
    }

    // -------------------------------------------------------------------------------------
    // PUBLIC: Define an array of list items ({caption: "", value: ""}) to show when focused
    // -------------------------------------------------------------------------------------
    function ListDefine(list) {
      mOptions.list = list;

      // Recreate List
      RecreateList();
      UpdateElement();

    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.RadioButtonList.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // ----------------
    // PUBLIC: Validate
    // ----------------
    function Validate() {
      // Initialise
      var message = "";
      var valid = true;

      // Ensure has value
      if (!mOptions.allowBlank && mValue === null) {
        valid = false;
        message = mOptions.blankValidationMessage;
      }

      // Update element
      if (valid) {
        ValidationSet(true, "", false);
      }
      else {
        ValidationSet(false, message, false);
      }

      return valid;
    }

    // ----------------------------
    // PUBLIC: Set validation state
    // ----------------------------
    function ValidationSet(isValid, validationText, validationTextIsHtml) {
      mIsValid = isValid;
      if (validationText === undefined) mValidationText = ""; else mValidationText = validationText;
      if (validationTextIsHtml === undefined) mValidationTextIsHtml = false; else mValidationTextIsHtml = validationTextIsHtml;

      // Update element
      UpdateElement();
    }



    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "RadioButtonList",

      AllowBlank: AllowBlank,
      AutoReadOnly: AutoReadOnly,
      caption: Caption,
      Element: Element,
      Focus: Focus,
      ItemEnabled: ItemEnabled,
      ItemVisible: ItemVisible,
      ListFromArray: ListFromArray,
      ReadOnly: ReadOnly,
      Validate: Validate,
      ValidationSet: ValidationSet,
      Value: Value,
      Visible: Visible,
      VisibleRow: VisibleRow,
    };

    // Associate this control to HTML input element (for container validation)
    mWrapperElement.prop("is-control", _self);

    return _self;
  }

  // =========================
  // PUBLIC: FileUpload object
  // =========================
  function FileUpload(e, options) {

    var mButtonAddDocumentManager;
    var mButtonAddFile;
    var mButtonAddResource;
    var mButtonsElement;
    var mElement;
    var mElementDropFile;
    var mElementFileInputs;
    var mElementFileList;
    var mElementRow;
    var mFileInputs = [];
    var mFileList = [];
    var mIsValid = true;
    var mLabelElement;
    var mOptions;
    var mValidationElement;
    var mWrapperElement;

    // Extend options with defaults
    FileUploadDefaults = {
      allowFile: true,
      allowDocumentManager: true,
      allowResource: true,

      resourceOptions: { includeAll: false, includeAllowAsEmailAttachment: true },

      documentManagerSourceType: "",
      documentManagerSourceId: "",

      maxFiles: 10,
      visible: true,

      onChange: null,
    };
    mOptions = $.extend({}, FileUploadDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.FileUpload: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Wrap element
    mElement.wrap("<span style='padding:0; margin:0;' controltype='fileupload'/>");
    mWrapperElement = $(mElement.parent());

    // Child elements
    mButtonsElement = $("<div class='is-fileupload-buttons'></div>");
    mElement.append(mButtonsElement);
    mValidationElement = $("<div class='is-fileupload-validation'></div>");
    mElement.append(mValidationElement);
    mElementFileList = $("<div class='is-fileupload-filelist'></div>");
    mElement.append(mElementFileList);
    mElementFileInputs = $("<div class='is-fileupload-fileinputs'></div>");
    mElement.append(mElementFileInputs);

    // Find associated label
    el = $("label[for='" + id + "']");
    mLabelElement = (el.length == 0 ? null : $(el[0]));

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Layout
      mElement.addClass("is-fileupload");

      // Add Buttons
      mButtonsElement.children().remove();
      if (mOptions.allowFile) {
        mButtonAddFile = $("<button class='is-button'>Browse...</button>");
        mButtonsElement.append(mButtonAddFile);
        mButtonAddFile.click(Add_File);
      }
      if (mOptions.allowResource) {
        mButtonAddResource = $("<button class='is-button'>Resource</button>");
        mButtonsElement.append(mButtonAddResource);
        mButtonAddResource.click(Add_Resource);
      }
      if (mOptions.allowDocumentManager && mOptions.documentManagerSourceType && mOptions.documentManagerSourceId) {
        mButtonAddDocumentManager = $("<button class='is-button'>Document Manager</button>");
        mButtonsElement.append(mButtonAddDocumentManager);
        mButtonAddDocumentManager.click(Add_DocumentManager);
      }
      if (mOptions.allowFile && !Runtime_IsMobileBrowser) {
        mElementDropFile = $("<div class='is-drop-files'>Or drop files here</div>");
        mButtonsElement.append(mElementDropFile);

        // Events
        mElementDropFile.bind("dragenter", function (e) {
          e.stopPropagation();
          e.preventDefault();
          mElementDropFile.addClass("dragover");
          return false;
        });
        mElementDropFile.bind("dragover", function (e) {
          e.preventDefault();
          e.originalEvent.dataTransfer.dropEffect = "copy";
        });

        mElementDropFile.bind("dragleave", function (e) {
          e.stopPropagation();
          e.preventDefault();
          mElementDropFile.removeClass("dragover");
          return false;
        });
        mElementDropFile.bind("drop", function (e) {
          e.stopPropagation();
          e.preventDefault();
          mElementDropFile.removeClass("dragover");

          for (var i = 0; i < e.originalEvent.dataTransfer.files.length; i++) {
            var file = e.originalEvent.dataTransfer.files[i];

            mFileList.push({ type: "file", file: file, name: file.name, size: file.size });
          }

          // Update File List
          UpdateElement_FileList(true);

          return false;
        });
      }

      // Visibility
      if (mOptions.visible) {
        mWrapperElement.show();
      }
      else {
        mWrapperElement.hide();
      }

      // File List
      UpdateElement_FileList(false);
    }

    function UpdateElement_FileList(notify) {
      // Initialise
      mElementFileList.children().remove();

      // Validation warning
      var msg = ValidationMessage();
      if (msg) {
        mValidationElement.html(msg);
        mValidationElement.show();
        mIsValid = false;
      }
      else {
        mValidationElement.hide();
        mIsValid = true;
      }

      for (var i = 0; i < mFileList.length; i++) {
        var item = mFileList[i];

        var e = $("<div class='item'><div>");

        var ename = $("<div class='name'></div>");
        ename.text(item.name);
        e.append(ename);

        var esize = $("<div class='size'></div>");
        var size = item.size;
        if (size) {
          if (size == 0) {
            size = "0 KB";
          }
          else if (size < 1024) {
            size = "1 KB";
          }
          else if (size >= 1024 * 1024) {
            size = Math.ceil(size / (1024 * 1024)) + " MB";
          }
          else {
            size = Math.ceil(size / 1024) + " KB";
          }
        }
        else {
          size = "unknown";
        }
        esize.text(size);
        e.append(esize);

        var eremove = $("<div class='remove'></div>");
        e.append(eremove);

        (function (index) {
          eremove.click(function () {
            // Remove
            mFileList.splice(index, 1);

            // Rebuild list
            UpdateElement_FileList(true);
          });
        })(i);

        mElementFileList.append(e);
      }

      // Notify
      if (notify && mOptions.onChange) {
        var e = {};
        mOptions.onChange(_self, e);
      }
    }

    // --------------------
    // PRIVATE: Add methods
    // --------------------
    function Add_DocumentManager() {
      widget.UI.SelectDocumentManagerFile(mOptions.documentManagerSourceType, mOptions.documentManagerSourceId, {}, Add_DocumentManager_Done);
    }
    function Add_DocumentManager_Done(fileName) {
      mFileList.push({ type: "documentmanager", name: fileName });

      // Rebuild file list
      UpdateElement_FileList(true);
    }

    function Add_File() {
      var id = "fi" + CreateGuid(true);
      var fi = $("<input type='file' id='" + id + "' style='display:none'/>");
      if (mOptions.maxFiles > 1) fi.attr("multiple", "multiple");
      //var fil = 
      //fi.attr("accept", accept);
      mFileInputs.push(fi);
      mElementFileInputs.append(fi);

      // Rebuild files list on change
      fi.change(function (e) {
        for (var i = 0; i < fi[0].files.length; i++) {
          var file = fi[0].files[i];
          mFileList.push({ type: "file", file: file, name: file.name, size: file.size });
        }

        // Update File List
        UpdateElement_FileList(true);

      });

      // Trigger click event
      fi.click();
    }

    function Add_Resource() {
      widget.UI.SelectResource(mOptions.resourceOptions, Add_Resource_Done);
    }
    function Add_Resource_Done(resourceId, description, resourceType, sizeBytes) {
      mFileList.push({ type: "resource", resourceId: resourceId, resourceType: resourceType, name: description, size: sizeBytes });

      // Rebuild file list
      UpdateElement_FileList(true);
    }
    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        if (mLabelElement) return mLabelElement.text(); else return "";
      }
      else {
        // Set
        if (mLabelElement) mLabelElement.text(value);
      }
    }

    // --------------------------------
    // PUBLIC: The jQuery Input Element
    // --------------------------------
    function Element() {
      return mElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
    }

    // ----------------------------------------------------------
    // PUBLIC: Refresh to enable access to Document Manager files
    // ----------------------------------------------------------
    function RefreshDocumentManager(sourceType, sourceId) {
      if (sourceType != mOptions.documentManagerSourceType || sourceId != mOptions.documentManagerSourceId) {
        mOptions.documentManagerSourceType = sourceType;
        mOptions.documentManagerSourceId = sourceId;

        // Refresh
        UpdateElement();
      }
    }

    // --------------
    // PUBLIC: Clear 
    // --------------
    function Clear() {
      // Remove all file elements
      mFileList = [];

      // Rebuild list
      UpdateElement_FileList(false);
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Visible Row property (i.e., make the parent row visible/ hidden)
    // ------------------------------------------------------------------------
    function VisibleRow(value) {
      // Get Row Element
      if (!mElementRow) {
        mElementRow = mElement.closest("tr");
        if (mElementRow.length == 0) {
          console.warn("widget_ui.FileUpload.VisibleRow: no parent row element found.");
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return (mElementRow.css("visibility").toUpperCase() != "HIDDEN" && mElementRow.css("display").toUpperCase() != "NONE");
      }
      else {
        // Set
        if (value) {
          mElementRow.css("display", "table-row");
          mElementRow.css("visibility", "");
        }
        else {
          mElementRow.css("display", "none");
          mElementRow.css("visibility", "hidden");
        }
      }
    }

    // -----------------------------------------
    // PUBLIC: Get File data required for upload
    // -----------------------------------------
    function GetFileData() {
      var arr = [];

      for (var i = 0; i < mFileList.length; i++) {
        var item = mFileList[i];

        switch (item.type) {
          case "documentmanager":
            arr.push({ special: "DocumentManager:" + mOptions.documentManagerSourceType + "~" + mOptions.documentManagerSourceId + "~" + item.name });
            break;

          case "file":
            arr.push(item.file);
            break;

          case "resource":
            arr.push({ special: "Resource:" + item.resourceId });
            break;
        }
      }

      return arr;
    }

    // ------------------------
    // PUBLIC: Is control valid
    // ------------------------
    function IsValid() {
      return mIsValid ? true : false;

    }

    // --------------------------
    // FRIEND: Validation Message
    // --------------------------
    function ValidationMessage() {
      if (mFileList.length > mOptions.maxFiles) {
        switch (mOptions.maxFiles) {
          case 1:
            return "You are limited to <b>1</b> file. Please remove any additional files.";

          default:
            return  "You are limited to <b>" + mOptions.maxFiles + "</b> files. Please remove additional files.";
        }
      }

      return "";
    }



    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "FileUpload",

      caption: Caption,
      Clear: Clear,
      Element: Element,
      Focus: Focus,
      GetFileData: GetFileData,
      IsValid: IsValid,
      RefreshDocumentManager: RefreshDocumentManager,
      Visible: Visible,
      VisibleRow: VisibleRow,

      // Friend
      ValidationMessage: ValidationMessage,
    };

    // Associate this control to HTML input element (for container validation)
    mWrapperElement.prop("is-control", _self);

    return _self;
  }



  // =================================
  // PUBLIC: Charts sub-object - BEGIN
  // =================================
  var mCharts = {
    // Properties
    mAvailableApexCharts: false,

    // -------------------
    // PRIVATE: Initialise
    // -------------------
    Initialise: function () {
      // Detect available chart libraries
      // NOTE: Must use jQuery's delayed load to ensure available, e.g., if hosted on CDN (Externally Hosted Widgets)
      $(function () {
        try {
          mAvailableApexCharts = !(window.ApexCharts === undefined);
        }
        catch (ex) { }
      });
    },

    // -------------------------------------------
    // PRIVATE: Show library not available warning
    // -------------------------------------------
    ShowNotAvailableWarning: function (libraryName) {
      window.alert("The '" + libraryName + "' chart library is not available to this HTML Widget or Portal.\n\nEnsure the Options page of the relevant form has the '" + libraryName + "' option checked under the 'Resources required' section.");
    },

    // =====================================
    // PUBLIC: ApexCharts sub-object - BEGIN
    // =====================================
    ApexCharts: {
      // --------------------------------------------------------------
      // PUBLIC: Initialise and call function when library is available
      // --------------------------------------------------------------
      Initialise: function (callback) {
        // NOTE: ApexCharts does not require any type of callback but I have included this method for possible compatibility with other libraries
        callback();
      },

      // ---------------------------------------------------
      // PUBLIC: Create a Chart (shortcut to new ApexCharts)
      // ---------------------------------------------------
      Chart: function (e, options) {
        // Available?
        if (!mAvailableApexCharts) {
          widget.UI.Charts.ShowNotAvailableWarning("ApexCharts");
          return;
        }

        // Get Element and validate (may be element or id)
        var id;
        if (typeof e == "string") {
          id = e;
          e = $("#" + id);
        }
        else {
          id = $(e).attr("id");
        }
        var el = $(e);
        if (el.length == 0) {
          console.warn("widget_ui.Charts.ApexCharts.Chart: Element '" + id + "' not found.");
          return;
        }

        // Extend/ normalise options
        // TODO: Will probably use ApexCharts as the model so no need to "normalise" the options for this chart provider
        options = $.extend({},
          {
            chart: {
              type: "pie",
              fontFamily: "'Open Sans', Sans-serif, 'Helvetica Neue', Helvetica, Verdana, Arial",
            },
            series: [],
          },
          options);

        // Use widget defined default chart colours?
        if (!options.colors && widget.Options.defaultChartColours) {
          options.colors = widget.Options.defaultChartColours.split(",");
        }

        // Create Chart
        return new ApexCharts(el[0], options);
      },

      // ------------------------------------------------------------------------------------------------
      // PUBLIC: Create an XY Series (for bar-charts etc) from labels and values (used by pie-charts etc)
      // ------------------------------------------------------------------------------------------------
      CreateXYSeries: function (labels, values, colours) {
        var series = [];

        for (var i = 0; i < labels.length; i++) {
          var item = { x: labels[i], y: values[i] };
          series.push(item);

          // Colour (optional)
          if (colours) item.fillColor = colours[i];
        }

        return series;
      },

      // -------------------------------------------------------------------------
      // PUBLIC: Create a Bar Chart (Apex Chart with type of 'bar' and horizontal)
      //
      // ref: https://apexcharts.com/docs/chart-types/bar-chart/
      // -------------------------------------------------------------------------
      BarChart: function (e, options) {
        // Force Bar Chart
        options = $.extend({}, {
          chart: {
            type: "bar",
            toolbar: { show: false },
          },

          plotOptions: {
            bar: {
              horizontal: true
            }
          },
        }, options);

        return widget.UI.Charts.ApexCharts.Chart(e, options);
      },

      // -------------------------------------------------------------
      // PUBLIC: Create a Bar Chart (Apex Chart with type of 'bar')
      //
      // ref: https://apexcharts.com/docs/chart-types/bar-chart/
      // -------------------------------------------------------------
      ColumnChart: function (e, options) {
        // Force Column Chart
        options = $.extend({}, {
          chart: {
            type: "bar",
            toolbar: { show: false },
          },
        }, options);

        return widget.UI.Charts.ApexCharts.Chart(e, options);
      },

      // --------------------------------------------------------------
      // PUBLIC: Create a Donut Chart (Apex Chart with type of 'donut')
      //
      // ref: https://apexcharts.com/docs/chart-types/pie-donut/
      // --------------------------------------------------------------
      DonutChart: function (e, options) {
        // Force Donut Chart
        options = $.extend({}, { chart: { type: "donut" } }, options);

        return widget.UI.Charts.ApexCharts.Chart(e, options);
      },

      // ----------------------------------------------------------
      // PUBLIC: Create a Pie Chart (Apex Chart with type of 'pie')
      //
      // ref: https://apexcharts.com/docs/chart-types/pie-donut/
      // ----------------------------------------------------------
      PieChart: function (e, options) {
        // Force Pie Chart
        options = $.extend({}, { chart: { type: "pie" } }, options);

        return widget.UI.Charts.ApexCharts.Chart(e, options);
      },

      // -------------------------------------------------------------
      // PUBLIC: Create a Line Chart (Apex Chart with type of 'line')
      //
      // ref: https://apexcharts.com/docs/chart-types/line-chart/
      // -------------------------------------------------------------
      LineChart: function (e, options) {
        // Force Line Chart
        options = $.extend({}, {
          chart: {
            type: "line",
            toolbar: { show: false },
          },
        }, options);


        return widget.UI.Charts.ApexCharts.Chart(e, options);
      },

      // --------------------------------
      // PUBLIC: Create a Grid Visualiser
      // --------------------------------
      GridVisualiser: function (e, grid, options) {
        // Available?
        if (!mAvailableApexCharts) {
          widget.UI.Charts.ShowNotAvailableWarning("ApexCharts");
          return;
        }

        // Initialise
        var mGrid = grid;
        var mParent = widget.UI.Charts.ApexCharts; // NOTE: If we support multiple libraries, this can be passed in and the whole visualiser moved to the top-level - maybe!

        // Extend options with defaults
        var mOptions = $.extend({},
          {
            chartTypes: "Bar,Column,Donut,Pie", // For Custom charts

            defaultColours: "",
          },
          options);

        // Use widget defined default chart colours?
        if (!mOptions.defaultColours) {
          mOptions.defaultColours = widget.Options.defaultChartColours;

          if (!mOptions.defaultColours) {
            console.warn("widget_ui.Charts.ApexCharts.GridVisualiser: defaultColours unspecified. Default list being used.");
            mOptions.defaultColours = "#00876c,#439981,#6aaa96,#8cbcac,#aecdc2,#cfdfd9,#f1f1f1,#f1d4d4,#f0b8b8,#ec9c9d,#e67f83,#de6069,#d43d51,#00876c,#449a71,#6bac77,#91be80,#b5cf8a,#dae098,#fff1a9,#fad68c,#f6ba74,#f19d61,#ea8056,#e16051,#d43d51";
          }
        }

        // Get Element and validate (may be element or id)
        var id;
        if (typeof e == "string") {
          id = e;
          e = $("#" + id);
        }
        else {
          id = $(e).attr("id");
        }
        var el = $(e);
        if (el.length == 0) {
          console.warn("widget_ui.Charts.ApexCharts.GridVisualiser: Element '" + id + "' not found.");
          return;
        }

        // Create controls
        var mVisualisationText, mVisualisation;
        var mElement = $(el[0]);
        var mUniqueId = CreateGuid(true);
        mElement.append("<div class='is-grid-visualiser is-dock-fill'><div class='buttons'><input id='cboVisualisation" + mUniqueId + "'/> <input id='cboChartType" + mUniqueId + "'/> <input id='cboColumn1" + mUniqueId + "'/> <input id='cboColumn2" + mUniqueId + "'/> <span style='font-size:12px;'><input id='chkExcludeNone" + mUniqueId + "' type='checkbox' /></span></div > <div class='main-chart' style='max-width:100%'><div class='main-chart-canvas' style='max-width:100%'></div></div></div > ");
        var C = {};

        C.cboVisualisation = widget.UI.ComboBox("cboVisualisation" + mUniqueId, {
          blankTip: "Visualisation",
          limitToList: true,
          width: "22em",

          onChange: function (sender, e) {
            // Handled
            if (e) e.ChangeHandled = true;

            // Refresh
            mVisualisationText = sender.Text();
            if (sender.ListIndex() == -1) {
              mVisualisation = null;
            }
            else {
              mVisualisation = mOptions.visualisations[sender.ListIndex()];
            }
            C.chkExcludeNone.Value(false);
            _self._Layout();
            _self._RedrawMainChart();
          }

        });
        C.cboChartType = widget.UI.ComboBox("cboChartType" + mUniqueId, {
          blankTip: "Chart",
          limitToList: true,
          width: "6em",

          onChange: function (sender, e) {
            // Handled
            if (e) e.ChangeHandled = true;

            // Refresh
            _self._Layout();
            _self._RedrawMainChart();
          }
        });
        C.cboColumn1 = widget.UI.ComboBox("cboColumn1" + mUniqueId, {
          blankTip: "Column",
          limitToList: true,

          onChange: function (sender, e) {
            // Handled
            if (e) e.ChangeHandled = true;

            // Refresh
            C.chkExcludeNone.Value(false);
            _self._Layout();
            _self._RedrawMainChart();
          }
        });
        C.cboColumn2 = widget.UI.ComboBox("cboColumn2" + mUniqueId, {
          blankTip: "Column",
          limitToList: true,

          onChange: function (sender, e) {
            // Handled
            if (e) e.ChangeHandled = true;

            // Refresh
            C.chkExcludeNone.Value(false);
            _self._Layout();
            _self._RedrawMainChart();
          }
        });
        C.chkExcludeNone = widget.UI.CheckBox("chkExcludeNone" + mUniqueId, {
          caption: "Exclude '[None]'?",

          onChange: function (sender, e) {
            // Refresh
            _self._Layout();
            _self._RedrawMainChart();
          }
        });

        C.divMainChart = $("div.main-chart", mElement);
        C.chartMain = null; // Created when first used


        // Return control
        var _self = {
          // ---------------
          // PUBLIC: Refresh
          // ---------------
          Refresh: function (options) {
            // Extend options?
            if (options) mOptions = $.extend({}, mOptions, options);

            // Visualisations List
            if (mOptions.visualisations && mOptions.visualisations.length != 0) {
              C.cboVisualisation.ListFromCollection(mOptions.visualisations, "caption");

              // Default?
              //TODO: From persisted?
              if (!C.cboVisualisation.Text()) {
                for (var i = 0; i < mOptions.visualisations.length; i++) {
                  var item = mOptions.visualisations[i];
                  if (item.default) {
                    C.cboVisualisation.Text(item.caption);
                    break;
                  }
                }

                // Custom?
                if (C.cboVisualisation.Text() == "[Custom]") {

                }
              }
            }
            else {
              C.cboVisualisation.ListFromCsvString("");
            }
            if (mOptions.allowCustomVisualisation) C.cboVisualisation.ListAdd("[Custom]");

            // Columns List
            var columns = mGrid.GetColumnsList(true);
            var list = [];
            for (var i = 0; i < columns.length; i++) {
              var c = columns[i];
              if (c.key.startsWith("UserData") && c.caption) {
                list.push(c.key + " [" + c.caption + "]");
              }
              else {
                list.push(c.key);
              }
            }
            C.cboColumn1.ListFromArray(list);
            C.cboColumn2.ListFromArray(list);
            //C.cboColumn1.ListFromCollection(mGrid.GetColumnsList(true), "key");
            //C.cboColumn2.ListFromCollection(mGrid.GetColumnsList(true), "key");

            // Chart Types List
            C.cboChartType.ListFromCsvString(mOptions.chartTypes);
            if (!C.cboChartType.Text()) C.cboChartType.Text("Pie");

            // Layout
            _self._Layout();

            // Draw Chart?
            mVisualisationText = C.cboVisualisation.Text();
            if (C.cboVisualisation.ListIndex() == -1) {
              mVisualisation = null;
            }
            else {
              mVisualisation = mOptions.visualisations[C.cboVisualisation.ListIndex()];
            }
            _self._Layout();
            _self._RedrawMainChart();
          },

          // --------------------------
          // PRIVATE: Redraw Main Chart
          // --------------------------
          _RedrawMainChart: function () {
            // Initialise
            var options = {};

            // Get chart details
            var chartType = C.cboChartType.Text().toLowerCase();
            var column1 = C.cboColumn1.Text();
            var columnCaption1 = column1;
            var column2 = C.cboColumn2.Text();
            var columnCaption2 = column2;
            var visualisation = mVisualisation || { chartType: chartType };
            var excludeNone = C.chkExcludeNone.Value();
            var hasNone = false;

            // Remove column captions (e.g., UserData columns)
            var n = column1.indexOf(" [");
            if (n != -1) {
              columnCaption1 = column1.substr(n + 2);
              columnCaption1 = columnCaption1.substr(0, columnCaption1.length - 1);
              column1 = column1.substr(0, n);
            }
            n = column2.indexOf(" [");
            if (n != -1) {
              columnCaption2 = column2.substr(n + 2);
              columnCaption2 = columnCaption2.substr(0, columnCaption2.length - 1);
              column2 = column2.substr(0, n);
            }

            // Clear chart type if not enough information specified to satisfy [Custom] chart
            if (mVisualisationText == "[Custom]") {
              switch (chartType) {
                default:
                  // ###
                  // All
                  // ###
                  if (!column1) {
                    chartType = "";
                  }
                  else {
                    visualisation.labelColumn = column1;
                    visualisation.seriesColumn = column2 || column1;
                    visualisation.caption = columnCaption1;
                    if (column2) visualisation.caption += " \\ " + columnCaption2;
                  }
                  break;
              }
            }

            // Create chart
            if (!chartType) {
              // Hide
              C.divMainChart.hide();
              return;
            }
            else {
              // Show
              C.divMainChart.show();

              // Tidy-up
              C.divMainChart.removeClass("square");

              // Get data
              var sort = visualisation.sort === false ? false : true;
              var data = mGrid.GetColumnDataForPieChart(visualisation.labelColumn, visualisation.seriesColumn || visualisation.labelColumn, excludeNone, sort);
              if (!excludeNone) {
                for (var i = 0; i < data.labels.length; i++) {
                  if (data.labels[i] == "[None]") {
                    hasNone = true;
                    break;
                  }
                }
              }

              // Get colours
              var colours = [];
              var customColours = false;
              if (visualisation.labelColumn && visualisation.labelColumn.indexOf("Colour") != -1) {
                customColours = true;

                for (var i = 0; i < data.labels.length; i++) {
                  var colour = data.labels[i];
                  switch (colour) {
                    case "[None]":
                      colours.push("#b0b0b0");
                      break;

                    default:
                      // NOTE: ApexCharts does not handle named colours well
                      colour = widget.UI.HtmlNamedColourToRgb(colour);
                      colours.push(colour);
                  }
                }
              }
              else {
                // Default colours
                // NOTE: Ensure '[None]' is consistently coloured
                colours = mOptions.defaultColours;
                if (data.labels.length > 0 && data.labels[0] === "[None]") colours = "#b0b0b0," + colours;
                colours = colours.split(",");
              }

              // Create Chart
              switch (chartType) {
                case "bar":
                  // ###
                  // Bar
                  // ###
                  var seriesXY = widget.UI.Charts.ApexCharts.CreateXYSeries(data.labels, data.values, customColours ? colours : undefined);

                  var options = {
                    chart: {
                      type: "bar",
                      height: "90%",
                      width: "90%",
                    },
                    legend: { show: true, position: "bottom", fontSize: "9px" },

                    series: [{
                      name: visualisation.seriesColumn,
                      data: seriesXY
                    }],
                    labels: [],

                    plotOptions: {
                      bar: {
                        horizontal: true
                      }
                    },
                  }

                  // Show actual values
                  if (!options.dataLabels) options.dataLabels = {};
                  options.dataLabels.formatter = function (val) {
                    return val;
                  };

                  break;

                case "column":
                  // ######
                  // Column
                  // ######
                  var seriesXY = widget.UI.Charts.ApexCharts.CreateXYSeries(data.labels, data.values, customColours ? colours : undefined);

                  var options = {
                    chart: {
                      type: "bar",
                      height: "95%",
                      width: "95%",
                    },
                    legend: { show: true, position: "bottom", fontSize: "9px" },

                    series: [{
                      name: visualisation.seriesColumn,
                      data: seriesXY
                    }],
                    labels: [],

                    plotOptions: {
                      bar: {
                        horizontal: false
                      }
                    },
                  }

                  // Show actual values
                  if (!options.dataLabels) options.dataLabels = {};
                  options.dataLabels.formatter = function (val) {
                    return val;
                  };

                  break;

                case "donut":
                case "pie":
                  // ##########
                  // Pie/ Donut
                  // ##########
                  options = {
                    chart: {
                      type: chartType,
                      height: "95%",
                      width: "100%",
                      toolbar: {
                        show: true
                      }
                    },
                    series: data.values,
                    labels: data.labels,

                    colors: colours,

                    legend: {
                      show: true,
                      position: "right",
                      fontSize: "9px",
                      formatter: function (seriesName, opts) {
                        return [seriesName, "&nbsp;&nbsp;<b>", opts.w.globals.series[opts.seriesIndex] + "</b>"];
                      },
                    }
                  };

                  // Show values as percentage or actual value
                  if (!options.dataLabels) options.dataLabels = {};
                  options.dataLabels.formatter = function (val, { seriesIndex, dataPointIndex, w }) {
                    if (visualisation.seriesColumn == visualisation.labelColumn) {
                      return val.toFixed(1) + "%";
                    }
                    else {
                      return w.config.series[seriesIndex];
                    }
                  };

                  // Square
                  C.divMainChart.addClass("square");
                  break;

                default:
                  console.warn("widget.UI.Charts.ApexCharts.GridVisualiser: Unhanded chart type '" + visualisation.chartType + "'");
              }

              // Titles
              var title = mOptions.title || "";
              if (visualisation.caption) title += " (" + visualisation.caption + ")";
              options.title = { text: title };

              var subTitle = mOptions.subTitle || "";
              options.subtitle = { text: subTitle };

              // Small device tweaks (J031665)
              if (window.innerWidth < 480 || window.innerHeight < 480) {
              //  options.title = undefined;
              //  options.subtitle = undefined;

                if (options.chart && options.chart.toolbar) {
                  options.chart.toolbar.show = false;
                }

                if (options.legend) {
                  options.legend.position = "bottom";
                  options.legend.height = 40;
                }
              }

              // Other
              options.chart.fontFamily = "'Open Sans', Sans-serif, 'Helvetica Neue', Helvetica, Verdana, Arial";
            }

            // Update and render
            if (C.chartMain) {
              C.chartMain.updateOptions(options);
            }
            else {
              C.chartMain = mParent.Chart($("> div.main-chart-canvas", C.divMainChart), options);
              C.chartMain.render();
            }

            // Show/ hide 'Exclude None' option
            if (excludeNone || hasNone) {
              C.chkExcludeNone.Visible(true);
            }
            else {
              C.chkExcludeNone.Visible(false);
            }
          },

          // ---------------
          // PRIVATE: Layout
          // ---------------
          _Layout: function () {
            // Controls
            if (mVisualisationText == "") {
              C.cboChartType.Visible(false);
              C.cboColumn1.Visible(false);
              C.cboColumn2.Visible(false);
            }
            else if (mVisualisation) {
              if (mVisualisation.chartTypes !== "") {
                if (mVisualisation.chartTypes) {
                  C.cboChartType.ListFromCsvString(mVisualisation.chartTypes);
                }
                else {
                  C.cboChartType.ListFromCsvString(mOptions.chartTypes);
                }
                C.cboChartType.Visible(true);
              }
              else {
                C.cboChartType.Visible(false);
              }
              C.cboColumn1.Visible(false);
              C.cboColumn2.Visible(false);
            }
            else {
              C.cboChartType.Visible(true);
              C.cboColumn1.Visible(true);
              C.cboColumn2.Visible(true);
            }

            switch (C.cboChartType.Text()) {
              case "Pie":
                C.cboColumn1.BlankTip("Label");
                C.cboColumn2.BlankTip("Value");
                break;

              default:
                C.cboColumn1.BlankTip("Value A");
                C.cboColumn2.BlankTip("Value B");

            }
          },
        };

        return _self;
      }
    },
    // =====================================
    // PUBLIC: ApexCharts sub-object - END
    // =====================================
  };
  mCharts.Initialise();
  // =================================
  // PUBLIC: Charts sub-object - END
  // =================================



  // ================================
  // PUBLIC: Forms sub-object - BEGIN
  // ================================
  var mForms = {
    // -----------------------------
    // PUBLIC: Show Account Schedule
    // -----------------------------
    ShowAccountSchedule: function (options) {
      // Extend options with defaults
      options = $.extend({},
        {
          scheduleJson: null,
        }, options);

      // Validate
      // NOTE: Return false if failed

      // Request that Widget show this form
      widget.__requestForm("AccountSchedule", options);

      return true;
    },

    // ---------------------------
    // PUBLIC: Show Company Lookup
    // ---------------------------
    ShowCompanyLookup: function (options, doneCallback, failCallback) {
      // Extend options with defaults
      options = $.extend({},
        {
          searchBy: "BusinessNumber",
          autoClose: true,

          businessNumber: null,
          legalName: null,
          organisationNumber: null,
          organisationName: null,
        }, options);

      // Validate
      // NOTE: Return false if failed

      // Request that Widget show this form
      widget.__requestForm("CompanyLookup", options, doneCallback, failCallback);

      return true;
    },

    // -----------------------------
    // PUBLIC: Show DataTable Viewer
    // -----------------------------
    ShowDataTableViewer: function (dataTableJson, options) {
      // Serialise dataTable (just in case it isn't a string)
      if (typeof dataTableJson !== "string") {
        try {
          dataTableJson = JSON.stringify(dataTableJson);
        }
        catch (ex) {
          window.alert("Failed to serialise object for displaying in the DataTable viewer.")
          return;
        }
      }

      // Extend options with defaults
      options = $.extend({},
        {
          dataTableJson: dataTableJson,
        }, options);

      // Validate
      // NOTE: Return false if failed

      // Request that Widget show this form
      widget.__requestForm("DataTableViewer", options);

      return true;
    },

    // ----------------------------------------------
    // FRIEND: Show Range Lookup from Parameters Host
    // ----------------------------------------------
    ShowRangeLookupFromParametersHost: function (options) {
      // Extend options with defaults
      options = $.extend({},
        {
          parametersHost: true,

          caption: "",
          rangeSource: "",
          rangeType: "Standard",
          rangeLookupSql: "",
          sqlWhere: "",
          idField: "",
          fieldList: "",
          sourceControl: null,
        }, options);

      var sourceControl = options.sourceControl;
      options.value = sourceControl.Text();
      options.sourceControl = ""; // Can't pass a reference to a control

      // Validate
      // NOTE: Return false if failed

      // Request that Widget show this form
      widget.__requestForm("RangeLookup", options,
        function (rangeText) {
          sourceControl.Text(rangeText);

          // Ensure Parameters Host updates the value internally
          if (sourceControl.NotifyChange) sourceControl.NotifyChange();
        },

        function () {
          window.alert("failed");
        });

      return true;
    },

    // -----------------------------------------------
    // PUBLIC: Show Range Lookup from Database details
    // -----------------------------------------------
    ShowRangeLookupFromDatabase: function (value, options, doneCallback, failCallback) {
      // Extend options with defaults
      options = $.extend({}, 
        {
          caption: "",
          rangeSingle: false,
        }, options);

      // Additional options
      options.rangeType = "DatabaseSql";
      options.value = value;

      // Validate
      // NOTE: Return false if failed

      // Request that Widget show this form
      widget.__requestForm("RangeLookup", options, doneCallback, failCallback);

      return true;
    },

    // -----------------------------------------------
    // PUBLIC: Show Range Lookup from a Standard Range
    // -----------------------------------------------
    ShowRangeLookupFromStandardRange: function (rangeName, value, options, doneCallback, failCallback) {
      // Extend options with defaults
      options = $.extend({},
        {
          caption: "",
          rangeSingle: false,
          rangeType: "Standard",
          sqlWhere: "",
        }, options);

      // Additional options
      options.rangeName = rangeName;
      options.value = value;

      // Validate
      // NOTE: Return false if failed

      // Request that Widget show this form
      widget.__requestForm("RangeLookup", options, doneCallback, failCallback);

      return true;
    },

    // -----------------
    // PUBLIC: Show HTML
    // -----------------
    ShowHtml: function (title, html, options) {
      // Extend options with defaults
      options = $.extend({},
        {
          height: "",
          width: "",
          maxWidth: "1024px",
          popupStyle: "",
          showWait: false,
          title: "HTML Viewer",
        }, options);

      // Defaults
      if (!options.height) options.height = "90%";
      if (!options.width) options.width = "90%";

      // Modal Options
      var modalOptions = {
        formType: "HtmlViewer",

        width: options.width,
        maxWidth: options.maxWidth,
        minWidth: options.minWidth,

        //allowMinimise: mModalStack.length == 0,

        height: options.height,
        maxHeight: options.maxHeight,
        minHeight: options.minHeight,

        title: title,

        //formKey: options.formKey,
        //appShortcutUrl: options.appShortcutUrl,
        //onAfterClose: options.onAfterClose,

        //parentModal: options.parentModal,
      };

      // Can we pass this on to finCC?
      // NOTE: This allows us to handle modals more elegantly and means that the HTML Viewer can close and re-open itself as the result of an application shortcut such as fetching additional PPSR Search results
      if (top.$UI) {
        console.log("Passing widget.UI.ShowHtml on to finPOWER Connect Cloud for more elegant handling");
        return top.$UI.CommonDialog().ShowHtml(title, html, modalOptions);
      }

      // Create Modal
      var Modal = widget.UI.Modal(modalOptions);

      // Show (content will be set in the next block)
      Modal.Show({ content: "" });

      // Update HTML
      if (options.showWait) {
        // Deferred. Caller will use the Modal.UpdateHtml method defined below
        Modal.ContentElement().children().remove();
        Modal.ContentElement().append("<div class='is-wait-block'><div class='is-wait'><div class='is-wait1'></div><div class='is-wait2'></div><div class='is-wait3'></div></div><label>Please wait...</label></div>");
      }
      else {
        ShowHtml_UpdateHtml(html, Modal, options);
      }

      // Add a special 'UpdateHtml' method to Modal (so asynchronous fetches can update)
      Modal.UpdateHtml = function (html) { ShowHtml_UpdateHtml(html, Modal, options); };

      // Return Modal (so asynchronous fetches can update)
      return Modal;


      function ShowHtml_UpdateHtml(html, modal, options) {
        var htmlComplete = false;
        var iframe = false;

        // Complete HTML documents must be shown in an IFRAME
        var s = html.toUpperCase();
        if (s.indexOf("<HTML") == -1) {
          // Partial HTML
          switch (options.popupStyle.toUpperCase()) {
            case "":
              // Tweak surrounding HTML based on which Summary Page 2 classes are being used
              if (s.indexOf("<DIV CLASS=\"IS-SUMMARYPAGE-2\"") != -1) {
                // Normal
              }
              else if (s.indexOf("IS-SUMMARYPAGE-BLOCKS") != -1) {
                // Blocks, e.g., Workflow Item Summary, Workflow Payment Arrangement Summary
              }
              else {
                // None
                html = "<div class='is-summarypage-2'>" + html + "</div>";
              }
              break;

            case "NOTE":
              html = "<div style='position:absolute;left:0;top:0;right:0;bottom:0;overflow:auto;-webkit-overflow-scrolling:touch;background-color:#FFF5A1'><div style='padding:8px'>" + html + "</div></div>";
              break;
          }
        }
        else {
          // Complete HTML
          htmlComplete = true;
          iframe = true;
        }

        // Force IFRAME?
        iframe = iframe || options.forceIFrame;

        // Update content
        if (iframe) {
          // IFRAME
          modal.ContentElement().children().remove();
          var contentIframe = $("<iframe style='position:absolute;width:100%;height:100%;border:0'/>");
          modal.ContentElement().append(contentIframe);

          // Smart background colouring
          if (true) {//options.smartBackgroundColour) {
            if (html.indexOf("is-summarypage-blocks") != -1) {
              // Summary page 2 blocks
              contentIframe.css({ "background-color": "#808080" });
            }
          }

          // Content
          var doc = contentIframe[0].contentDocument;
          doc.open();
          if (!htmlComplete) {
            doc.write("<!doctype html>");
            doc.write("<html>");
            doc.write("<head>");
            doc.write("<link rel='stylesheet' type='text/css' href='" + $Runtime.WebRoot() + "Content/SummaryPage2/summarypage_2.css'></link>");
            doc.write("<link rel='stylesheet' type='text/css' href='" + $Runtime.WebRoot() + "Content/SummaryPage2/summarypage_2_web.css'></link>");
            doc.write("</head>");
            doc.write("<body style='margin:0;padding:0'>"); // Cancel out any body padding etc from the stylesheet (added in the divs earlier in this function)
          }
          doc.write(html);
          if (!htmlComplete) {
            doc.write("</body>");
            doc.write("</html>");
          }
          doc.close();

          // Handle Application Shortcuts
          if (window.$Ash) {
            $Ash.HandleIframe(contentIframe[0]);
          }
          else {
            if (top.$Ash) {
              // Use Parent functionality (probably being used from an HTML Widget's Summary Page)
              console.log("Show HTML will handle Application Shortcuts using it's parent since no handler ($Ash) is available.");
              window.$Ash = top.$Ash;
              $Ash.HandleIframe(contentIframe[0]);
            }
            else {
              switch (widget.GetHostingContext()) {
                case "HtmlViewer":
                  // Desktop: Let the HTML Widget handle Application Shortcuts, e.g., Task Manager Workflow folder needs to send 'Workflow' Form Actions via the global handler
                  // NOTE: Code similar to $Ash.HandleDocument
                  var doc2 = $(doc);
                  doc2.off("click", "a[href^='app:'],a[href^='APP:']"); // Remove existing, e.g., when refreshing an HTML Widget's content
                  doc2.on("click", "a[href^='app:'],a[href^='APP:']", function () {
                    var e = $(this);
                    widget.ExecuteApplicationShortcutUrl(e.attr("href"), true);
                    // Prevent link from navigating
                    return false;
                  });

                  break;

                default:
                  window.alert("Show HTML cannot handle Application Shortcuts since no handler ($Ash) is available.");
                  break;
              }
            }
          }
        }
        else {
          // Inline
          // Smart background colouring
          if (true) {//options.smartBackgroundColour) {
            if (html.indexOf("is-summarypage-blocks") != -1) {
              // Summary page 2 blocks
              modal.ContentElement().css("background-color", "#808080");
            }
          }

          modal.ContentElement().html(html);
        }
      }
    },

    // --------------------------------------------------------
    // PUBLIC: Show URL (currently internal use only - website)
    // --------------------------------------------------------
    ShowUrl: function (title, url, options) {
      // Extend options with defaults
      options = $.extend({},
        {
          height: "",
          width: "",
          maxWidth: "1024px",
          popupStyle: "",
          showWait: false,
          title: "HTML Viewer",
        }, options);

      // Defaults
      if (!options.height) options.height = "90%";
      if (!options.width) options.width = "90%";

      // Modal Options
      var modalOptions = {
        formType: "HtmlViewer",

        width: options.width,
        maxWidth: options.maxWidth,
        minWidth: options.minWidth,

        //allowMinimise: mModalStack.length == 0,

        height: options.height,
        maxHeight: options.maxHeight,
        minHeight: options.minHeight,

        title: title,

        //formKey: options.formKey,
        //appShortcutUrl: options.appShortcutUrl,
        //onAfterClose: options.onAfterClose,

        //parentModal: options.parentModal,
      };

      //// Can we pass this on to finCC?
      //// NOTE: This allows us to handle modals more elegantly and means that the HTML Viewer can close and re-open itself as the result of an application shortcut such as fetching additional PPSR Search results
      //if (top.$UI) {
      //  console.log("Passing widget.UI.ShowHtml on to finPOWER Connect Cloud for more elegant handling");
      //  return top.$UI.CommonDialog().ShowHtml(title, html, modalOptions);
      //}

      // Create Modal
      var Modal = widget.UI.Modal(modalOptions);

      // Create IFRAME for content
      var name = "IFRAME_" + Modal.ModalId(); // Name this way so we can identify this iframe's parent Modal
      var html = "<iframe name='" + name + "' id='" + name + "' style='border:none; position:absolute; top:0; left:0; right:0; bottom:0; width:100%; height:100%' src='" + url + "'></iframe>";

      // Show
      Modal.Show({ content: html });

      // Return Modal (so asynchronous fetches can update)
      return Modal;
    },


    // ----------------------------------------
    // PUBLIC: Show another HTML Widget Modally
    // ----------------------------------------
    ShowHtmlWidgetModal: function (id, options, callback) {
      // Extend options with defaults
      options = $.extend({},
        {
          id: id,
        }, options);

      // finPOWER Connect Cloud-specific
      if (widget.GetHostingContext() == "WebInternal") {
        options.__modal = widget.__modal;

        if (options.closeOnEscape === undefined) options.closeOnEscape = false;

        // Store the callback (since we can't pass it around in JSON format!)
        widget.__widget.__SetWidgetNotifyParentCallback(callback);
      }
      else {
        // Store the callback (since we can't pass it around in JSON format!)
        __widgetNotifyParentCallback = callback;
      }

      // Validate
      // NOTE: Return false if failed

      // Close current?
      if (options.closeCurrent) widget.Close();

      // Request that Widget show this form
      widget.__requestForm("HtmlWidget", options);

      return true;
    },

  };
  // ================================
  // PUBLIC: Forms sub-object - END
  // ================================



  // ===============================================================
  // PUBLIC: Trim Functions (OBSOLETE: Use widget functions instead)
  // ===============================================================
  function Trim(text) {
    return widget.Trim(text);
  }
  function LTrim(text) {
    return widget.LTrim(text);
  }
  function RTrim(text) {
    return widget.RTrim(text);
  }

  // =================================
  // PUBLIC: Show an Alert Message Box
  // =================================
  function MsgBoxAlert(message, options, callback) {
    // Just in case!
    message = "" + message;

    if (!mDisableProxyControls && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      // -----------------------------------------------------------------------------------
      // Pass on to finPOWER Connect Cloud (so dialog is not confined to this Widget's area)
      // -----------------------------------------------------------------------------------
      window.parent.$UI.MsgBoxAlert(message, options, callback);
    }
    else {
      // ---------------------
      // Widget implementation
      // ---------------------

      // Initialise
      options = $.extend({}, MsgBoxDefaults, options);
      if (options.title == null) options.title = "Alert";
      if (options.icon == null) options.icon = "Warning";
      if (options.captionOk == null) options.captionOk = "OK";

      // Set default action button
      if (!options.focusActionId) options.focusActionId = "Ok";

      // Modal size
      if (!options.width) options.width = "80%";
      if (!options.height) options.height = "80%";

      if (message.length < 100 && message.indexOf("\n") == -1) {
        // Short messages, e.g., validation messages
        if (options.maxWidth == null) options.maxWidth = 320;
        if (options.maxHeight == null) options.maxHeight = 240;
      }
      else if (message.length < 200 && message.indexOf("\n") == -1) {
        // Short messages, e.g., validation messages
        if (options.maxWidth == null) options.maxWidth = 480;
        if (options.maxHeight == null) options.maxHeight = 320;
      }
      else if (message.length < 200 && message.indexOf("\n") != -1) {
        // Short messages, e.g., validation messages with line returns
        if (options.maxWidth == null) options.maxWidth = 480;
        if (options.maxHeight == null) options.maxHeight = 400;
      }
      else if (message.length < 500 && message.indexOf("\n") == -1) {
        // Medium messages, e.g., long confirmation messages
        if (options.maxWidth == null) options.maxWidth = 520;
        if (options.maxHeight == null) options.maxHeight = 480;
      }
      else {
        if (options.maxWidth == null) options.maxWidth = 800;
        if (options.maxHeight == null) options.maxHeight = 800;
      }

      // Create Modal
      var Modal = widget.UI.Modal(options);
      Modal.Actions().Define([
        { groupId: "[buttons]", actionId: "Ok", caption: options.captionOk },
      ]);
      Modal.OnAction(function (actionId) {
        switch (actionId) {
          case "Ok":
            Modal.Hide(true);
            if (callback) callback();
            break;
        }
      });

      // Define HTML Content
      var content = "";
      content += "<div class='is-msgbox'>";
      if (options.icon != null) {
        content += "<img src='" + widget.GetIconUrl(options.icon, 32) + "'/>";
      }
      if (options.heading) {
        content += "<h1>" + HtmlEncode(options.heading) + "</h1>";
      }
      if (options.messageIsHtml) {
        content += "<p>" + message + "<p>";
      }
      else {
        content += "<p>" + HtmlEncode(message) + "</p>";
      }
      content += "</div>";

      // Show
      Modal.Show({ content: content });
    }
  }

  // ==================================
  // PUBLIC: Show a Confirm Message Box
  // ==================================
  function MsgBoxConfirm(message, options, okCallback, cancelCallback) {
    // Just in case!
    message = "" + message;

    if (!mDisableProxyControls && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      // -----------------------------------------------------------------------------------
      // Pass on to finPOWER Connect Cloud (so dialog is not confined to this Widget's area)
      // -----------------------------------------------------------------------------------
      window.parent.$UI.MsgBoxConfirm(message, options, okCallback, cancelCallback);
    }
    else {
      // ---------------------
      // Widget Implementation
      // ---------------------

      // Initialise
      options = $.extend({}, MsgBoxDefaults, options);
      if (options.title == null) options.title = "Confirm";
      if (options.icon == null) options.icon = "Help";
      if (options.captionOk == null) options.captionOk = "OK";
      if (options.captionCancel == null) options.captionCancel = "Cancel";

      // Set default action button
      if (!options.focusActionId) options.focusActionId = "Ok";
      if (options.closeOnEscape == undefined) options.closeOnEscape = true;

      // Modal size
      if (!options.width) options.width = "80%";
      if (!options.height) options.height = "80%";

      if (message.length < 100 && message.indexOf("\n") == -1) {
        // Short messages, e.g., validation messages
        if (options.maxWidth == null) options.maxWidth = 320;
        if (options.maxHeight == null) options.maxHeight = 240;
      }
      else if (message.length < 200 && message.indexOf("\n") == -1) {
        // Short messages, e.g., validation messages
        if (options.maxWidth == null) options.maxWidth = 480;
        if (options.maxHeight == null) options.maxHeight = 320;
      }
      else if (message.length < 200 && message.indexOf("\n") != -1) {
        // Short messages, e.g., validation messages with line returns
        if (options.maxWidth == null) options.maxWidth = 480;
        if (options.maxHeight == null) options.maxHeight = 400;
      }
      else if (message.length < 500 && message.indexOf("\n") == -1) {
        // Medium messages, e.g., long confirmation messages
        if (options.maxWidth == null) options.maxWidth = 520;
        if (options.maxHeight == null) options.maxHeight = 480;
      }
      else {
        if (options.maxWidth == null) options.maxWidth = 800;
        if (options.maxHeight == null) options.maxHeight = 800;
      }

      // Create Modal
      var buttonStyle = options.icon == "Trash" ? "danger" : "";
      var Modal = widget.UI.Modal(options);
      var actions = [
        { groupId: "[buttons]", actionId: "Ok", caption: options.captionOk, buttonStyle: buttonStyle },
        { groupId: "[buttons]", actionId: "Cancel", caption: options.captionCancel },
      ];
      if (options.additionalButtons) {
        for (var i = 0; i < options.additionalButtons.length; i++) {
          var a = options.additionalButtons[i];
          a.groupId = "[buttons]";
          actions.unshift(a);
        }
      }

      Modal.Actions().Define(actions);
      Modal.OnAction(function (actionId) {
        switch (actionId) {
          case "Cancel":
            Modal.Hide(true);
            if (cancelCallback) cancelCallback(actionId);
            break;

          default:
            Modal.Hide(true);
            if (okCallback) okCallback(actionId);
            break;
        }
      });

      // Define HTML Content
      var content = "";
      content += "<div class='is-msgbox'>";
      if (options.icon != null) {
        content += "<img src='" + widget.GetIconUrl(options.icon, 32) + "'/>";
      }
      if (options.heading) {
        content += "<h1>" + HtmlEncode(options.heading) + "</h1>";
      }
      if (options.messageIsHtml) {
        content += "<p>" + message + "<p>";
      }
      else {
        content += HtmlEncode(message);
      }
      content += "</div>";

      // Show
      Modal.Show({ content: content });
    }
  }

  // ===============
  // MsgBox Defaults
  // ===============
  MsgBoxDefaults = {
    // Modal
    title: null,
    maxWidth: null,
    maxHeight: null,
    minWidth: null,
    minHeight: null,

    // Other
    heading: null,
    icon: null,
    messageIsHtml: false,
    captionOk: null,
    captionCancel: null,
  };

  // =======================================
  // PUBLIC: Show a Confirm List Message Box
  // =======================================
  function MsgBoxConfirmList(message, list, options, okCallback, cancelCallback) {
    // Just in case!
    message = "" + message;

    // Initialise
    options = $.extend({}, MsgBoxDefaults, options);
    if (options.title === null) options.title = "Confirmation Required";
    if (options.icon === null) options.icon = "Help";
    if (options.captionOk === null) options.captionOk = "OK";
    if (options.captionCancel === null) options.captionCancel = "Cancel";
    if (!options.maxHeight) {
      // Try for a sensible max height
      var rows = 0;
      for (var i = 0; i < list.length; i++) {
        var s = list[i];
        var lines = (s + "").split("\n");
        for (var j = 0; j < lines.length; j++) {
          rows += 1;
          if (lines[j].length > 60) {
            rows += Math.ceil(lines[j].length / 60);
          }
        }
      }
      options.maxHeight = 180 + (rows * 18);
      if (options.heading) options.maxHeight += 24;
    }

    if (!options.height) options.height = "95%";
    if (!options.width) options.width = "95%";
    if (!options.maxWidth) options.maxWidth = 800;

    // Create Modal
    var Modal = widget.UI.Modal(options);
    var actions = [
      { groupId: "[buttons]", actionId: "Ok", caption: options.captionOk, enabled: false },
      { groupId: "[buttons]", actionId: "Cancel", caption: options.captionCancel },
    ];
    Modal.Actions().Define(actions);

    Modal.OnAction(function (actionId) {
      switch (actionId) {
        case "Cancel":
          Modal.Hide(true);
          if (cancelCallback) cancelCallback();
          break;

        default:
          Modal.Hide(true);
          if (okCallback) okCallback();
          break;
      }
    });

    // Define HTML Content
    var content = "";
    content += "<div class='is-msgbox'>";
    if (options.icon != null) {
      content += "<img src='" + widget.GetIconUrl(options.icon, 32) + "'/>";
    }
    if (options.heading) {
      content += "<h1>" + HtmlEncode(options.heading) + "</h1>";
    }
    if (options.messageIsHtml) {
      content += "<p>" + message + "<p>";
    }
    else {
      content += HtmlEncode(message);
    }

    content += "<ul class='is-msgbox-confirm-list'>";
    content += "</ul>";

    content += "</div>";

    // Show
    Modal.Show({ content: content });


    // Add list items
    var checkedCount = 0;
    var e = $("ul.is-msgbox-confirm-list", Modal.ContentElement());

    for (var i = 0; i < list.length; i++) {
      var li = $("<li><input type='checkbox'/></li>");
      e.append(li);

      var chk = widget.UI.CheckBox($("input", li), {
        caption: list[i],
        captionWrap: true,
        onChange: function (chk) {
          // Count checked
          if (chk.Value()) checkedCount += 1; else checkedCount -= 1;

          // Enable action
          Modal.Actions().SetEnabled("OK", checkedCount == list.length);
          Modal.Refresh();
        }
      });
    }
  }

  // ============================================================
  // PUBLIC: Show a simple Confirm Message Box to delete a Record
  // ============================================================
  function MsgBoxConfirmDelete(message, options, okCallback, cancelCallback) {
    // Just in case!
    message = "" + message;

    if (!mDisableProxyControls && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      // Pass on to finPOWER Connect Cloud
      window.parent.$UI.MsgBoxConfirmDelete(message, options, okCallback, cancelCallback);
    }
    else {
      // Initialise
      options = $.extend({}, MsgBoxDefaults, options);
      if (options.title == null) options.title = "Confirm";
      if (options.heading == null) options.heading = "Delete";
      if (options.icon == null) options.icon = "Trash";
      if (options.captionOk == null) options.captionOk = "Delete";

      // Always cancel by default
      options.focusActionId = "Cancel";

      MsgBoxConfirm(message, options, okCallback, cancelCallback);
    }
  }

  // =============================================
  // PUBLIC: Show a simple Information Message Box
  // =============================================
  function MsgBoxInfo(message, options, callback) {
    // Just in case!
    message = "" + message;

    options = $.extend({}, MsgBoxDefaults, options);
    if (!options.icon) options.icon = "Information";
    if (!options.title) options.title = "Information";
    widget.UI.MsgBoxAlert(message, options, callback);
  }

  // ===============================
  // PUBLIC: Show a List Message Box
  // ===============================
  function MsgBoxList(message, list, options, listCallback) {
    // Just in case!
    message = "" + message;

    if (!mDisableProxyControls && widget.GetHostingContext() == "WebInternal" && window.parent && window.parent.$UI) {
      // Pass on to finPOWER Connect Cloud
      window.parent.$UI.MsgBoxList(message, list, options, listCallback);
    }
    else {
      // Normalise list options
      options = $.extend({}, {
        closeOnEscape: false,
        showClose: false,
        width: 480,
        height: "auto"
      }, options);

      // Create Modal
      var Modal = widget.UI.Modal(options);

      // Show
      Modal.Show({ content: "" });

      // FUDGE: IE does not size the height to auto, instead it hides the content (yet Edge does and other browsers are fine either way)
      Modal.ModalElement().css("display", "block");

      // Build HTML for Modal content
      var html = "";
      var selected = false;
      html += "<div id='divList' class='is-msgbox-list' tabindex='-1'>";
      if (message) {
        html += "<label id='message'>" + HtmlEncode(message) + "</label>";
      }
      html += "<ul id='ulList'>";

      for (var i = 0; i < list.length; i++) {
        // Extend options with defaults
        var item = $.extend({}, {
          caption: "",
          details: "",
          enabled: true,
          icon: "",
          disabledWarning: "",
        }, list[i]);

        // Add item
        var cssClass = "";
        html += "<li key='" + item.key + "' index='" + i + "'";
        if (!selected && item.enabled) {
          selected = true;
          cssClass += "is-sel ";
        }
        else if (!item.enabled) {
          cssClass += "disabled ";
        }
        if (item.icon) {
          cssClass += "icon ";
          var iconUrl = widget.GetIconUrl(item.icon, 32);
          iconUrl = iconUrl.replace(/\\/g, "/");  // Backslash to forward slash when running from local file system
          html += " style=\"background-image:url('" + iconUrl + "')\"";
        }
        if (cssClass) html += " class='" + cssClass + "'";
        html += ">";

        html += "<h1>" + HtmlEncode(item.caption) + "</h1>";

        if (item.details) {
          html += "<div>" + HtmlEncode(item.details) + "</div>";
        }
        if (!item.enabled && item.disabledWarning) {
          html += "<div class='warning'>" + HtmlEncode(item.disabledWarning) + "</div>";
        }
        html += "</li>";
      }
      html += "</ul>";
      html += "</div>";

      // Render
      Modal.RenderView(html);

      // Controls
      var divList = Modal.GetElement("divList");
      var ulList = Modal.GetElement("ulList");

      // Handle events
      divList.bind("keyup", function (e) {
        var item = $("li.is-sel", ulList);
        var index = parseInt(item.attr("index"));

        switch (e.keyCode) {
          case 13: // Enter
            Modal.Close();
            try {
              if (item.hasClass("disabled")) return;
              if (listCallback) listCallback(item.attr("key"));
            }
            catch (ex) { }
            return false;

          case 38: // Cursor Up
            if (index > 0) {
              item.removeClass("is-sel");
              $($("li", ulList)[index - 1]).addClass("is-sel");
            }
            return false;

          case 40: // Cursor Down
            if (index < list.length - 1) {
              item.removeClass("is-sel");
              $($("li", ulList)[index + 1]).addClass("is-sel");
            }
            return false;
        }
      });

      $("li", ulList).click(function (e) {
        $("li", ulList).removeClass("is-sel");
        var item = $(this);
        item.addClass("is-sel");
        Modal.Close();
        try {
          if (item.hasClass("disabled")) return;
          if (listCallback) listCallback(item.attr("key"));
        }
        catch (ex) { }
      });

      // Focus
      var ti = window.setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        divList.focus();
      }, 100);

      // Ensure we keep focus (so cursor keys and Esc work as expected)
      divList.on("blur", function (e) {
        // Re-focus (this is a Modal so shouldn't interfere with anything else)
        divList.focus();
      });
    }
  }

  // ==========================================================================================
  // PUBLIC: Insert spaces within a camel-cased String (OBSOLETE: Use widget functions instead)
  // ==========================================================================================
  function SplitWordsAtCapitals(s, upperCaseFirstLetter, splitAtNumbers) {
    return widget.SplitWordsAtCapitals(s, upperCaseFirstLetter, splitAtNumbers);
  }

  // ===============================================================================
  // PUBLIC: Get an Array from a CSV String (OBSOLETE: Use widget functions instead)
  // ===============================================================================
  function ArrayFromCsvString(sourceString) {
    return widget.ArrayFromCsvString(sourceString);
  }

  // ========================================================================
  // PUBLIC: Get the table row that a control is hosted in as a jQuery object
  // ========================================================================
  function GetControlRow(control) {
    return control.Element().closest("tr");
  }

  // =======================================
  // PUBLIC: Dirty Tracking Enabled property
  // =======================================
  function DirtyTrackingEnabled(value) {
    if (value === undefined) {
      return mDirtyTrackingEnabled;
    }
    else {
      value = value === true;

      if (value != mDirtyTrackingEnabled) {
        mDirtyTrackingEnabled = value;

        // Start/ Stop
        if (mDirtyTrackingTimer) {
          window.clearInterval(mDirtyTrackingTimer);
          mDirtyTrackingTimer = null;
        }

        if (value && window.Form_IsDirty) {
          console.log("widget_ui: Dirty Tracking enabled.");

          mDirtyTrackingTimer = window.setInterval(function () {
            try {
              // Set Dirty state
              var dirty = window.Form_IsDirty();

              // Update Heading
              if (dirty === true || dirty === false) {
                if (widget && widget.__widget && widget.__widget.SetHeadingDirty) {
                  widget.__widget.SetHeadingDirty(dirty);
                }
              }
              else {
                // Just in case!
              }
            }
            catch (ex) {
              console.warn("widget_ui: Dirty Tracking error:\n\n" + ex);
            }
          }, 1000);
        }
      }
    }
  }

  // ===================================================
  // PUBLIC: Load a UI style to apply to Widget controls
  // ===================================================
  function LoadStyle(style, options, callback) {
    // Extend options
    var o = $.extend({}, {
      css: null,
      includeOtherCss: true,
    }, options);

    // Remove existing
    $("#_widget_style").remove();
    $("#_widget_style_top").remove();

    // Clearing?
    if (style === null || style === undefined) {
      if (callback) callback();
      return;
    }

    // Load Style
    // NOTE: Call regardless of whether style is blank so we can retrieve additional CSS if relevant
    var portalId = "";
    if (window.portal) portalId = portal.PortalId();
    widget._SystemGetString("GetUIStyle", { style: style, includeOtherCss: o.includeOtherCss, portalId: portalId },
      function (data) {
        // Inject into head
        data = "<div id='_widget_style'>" + data + "</div>";
        $("head").append(data);

        // Additional CSS supplied with options
        if (o.css) {
          // Inject
          var s = "<style type='text/css'>" + o.css + "</style>";
          $("#_widget_style").append(s);
        }

        // Shuffle '@import' directives to the very top
        if (data.indexOf("@import") != -1) {
          var re = /(?:@import)\s(?:url\()?\s?["\'](.*?)["\']\s?\)?(?:[^;]*);?/gi;
          var matches = data.match(re);

          if (matches.length != 0) {
            var imports = "";
            for (var i = 0; i < matches.length; i++) {
              if (imports) imports += "\n";
              imports += matches[i];
            }
            var top = "<div id='_widget_style_top'><style type='text/css'>" + imports + "</style></div>";
            $("head").prepend(top);
          }
        }

        if (callback) callback();
      },

      function (data) {
        if (document.location.href.indexOf("/WebAdmin") == -1) {
          widget.RegisterError("widget_ui.LoadStyle: Failed to retrieve Style information: " + data);
        }
        else {
          // Prevent Web Services admin from showing error notifications if Web Services are 'unavailable'
          console.warn("widget_ui.LoadStyle: Failed to retrieve Style information: " + data);
        }

        // Failed to load style. Not much we can do!
        if (callback) callback();
      });
  }

  // =====================
  // FRIEND: Create a GUID
  // =====================
  function CreateGuid(removeDashes) {
    return "xxxxxxxx-xxxx-xxxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
      var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
      var s = v.toString(16);
      if (removeDashes) s = s.replace(/-/g, "");
      return s;
    });
  }

  // ----------------------------------------------------------------------
  // PRIVATE: Show Form Actions Menu (shared by Modal and NonModal objects)
  // ----------------------------------------------------------------------
  function ShowFormActionsMenu(actionsContainerElement, actions, executeActionHandler) {
    var action, button, e, ei, ec, lastGroupId = "", iconUrl;

    // Clear existing
    actionsContainerElement.children().remove();

    // Add menu container and heading
    var container = $("<div class='is-no-select showing' tabindex='-1'></div>");
    actionsContainerElement.append(container);
    var caption = $("<div class='caption'>Actions</div>");
    var closeButton = $("<a><span class='is-symbol-close'></span></a>");
    closeButton.click(function () {
      actionsContainerElement.off("click");
      actionsContainerElement.hide();
    });
    caption.append(closeButton);
    container.append(caption);
    var body = $("<div></div>");
    container.append(body);

    // Add actions
    var links = $("<ul></ul>");
    body.append(links);
    for (var i = 0; i < actions.Actions().length; i++) {
      // Initialise
      action = actions.Actions()[i];

      // Visible?
      var visible = action.visible;
      if (!visible && action.repeatInGroupId && action.repeatInGroupId.toUpperCase() == "[BUTTONSOTHER]" && action.contextPageId && action.enabled) {
        // This is a page-based Action that is most likely hidden because we're not on the correct page but should still appear in the list
        visible = true;
      }

      if (visible) {
        if (action.groupId.substr(0, 1) != "[") {
          // New group?
          if (action.groupId != lastGroupId) {
            lastGroupId = action.groupId;

            e = $("<li class='heading'></li>");
            e.text(action.groupId);
            links.append(e);
          }

          // Action
          e = $("<li class='action'></li>");
          if (action.system) {
            e.addClass("system");
          }
          else {
            e.addClass("custom");
          }
          var eb = $("<button></button>");
          e.append(eb);
          if (!action.enabled) {
            e.addClass("disabled");
            eb.attr("disabled", "disabled");
          }
          if (action.icon) {
            ei = $("<img/>");
            eb.append(ei);
            iconUrl = widget.GetIconUrl(action.icon, 16);
            ei.attr("src", iconUrl);
          }
          ec = $("<span></span>");
          ec.text(action.caption);
          ec.attr("fincc_actionid", action.actionId); // For debugging purposes and for developers wishing to know the Ids of system actions
          eb.append(ec);
          links.append(e);

          // Handler
          if (action.enabled) {
            if (action.handler) {
              // Custom handler
              (function (action) { e.click(function () { actionsContainerElement.hide(); action.handler(); }); })(action);
            }
            else {
              // Default handler
              // NOTE: This will also automatically handle Custom Actions that are Application Shortcuts
              (function (action) { e.click(function () { actionsContainerElement.hide(); executeActionHandler(action.actionId, action.applicationShortcutUrl ? action.applicationShortcutUrl : action.data); }); })(action);
            }
          }
        }
      }
    }

    // Filter textbox?
    //var ftb = $("<input type='text' placeholder='Type to filter list'/>")
    //caption.append(ftb);

    //ftb.bind("keyup", function (e) {
    //  switch (e.keyCode) {
    //    case 27: // Escape
    //      ftb.val("");
    //      break;
    //  }

    //  // Filter
    //  $UI.FilterElements($("li", links), ftb.val());
    //});

    // Show
    actionsContainerElement.show();

    // Handle escape key and clicking background to close
    actionsContainerElement.on("click", function (e) {
      if (e.target === this) {
        closeButton.trigger("click");
      }
    });
    container.bind("keyup", function (e) {
      if (e.keyCode == 27) {
        if (e.target.tagName == "INPUT") {
          // Ignore escape in filter box
        }
        else {
          closeButton.trigger("click");
        }
      }
    });
    container.focus();

    // Focus on filter textbox unless in mobile
    //if (!Runtime_IsMobileBrowser) ftb.focus();

    // Remove 'showing' class used for animations
    var ti = window.setTimeout(function () {
      window.clearTimeout(ti);
      ti = null;

      container.removeClass("showing");
    }, 50);
  }


  // =================================
  // PUBLIC: Actions Collection object
  // =================================
  function ActionsCollection(actions) {

    var mActions = [];

    // Action Defaults
    var ActionDefaults = {
      buttonStyle: "",
      caption: "",
      alwaysShowCaption: false,
      applicationShortcutUrl: "",
      data: null, // Typically, either an Application Short OR Data is used
      checked: false,
      context: false,
      contextPageId: "",
      enabled: true,
      icon: "",
      groupId: "",
      repeatInGroupId: "",
      system: true,
      tooltipText: "",
      visible: true
    };

    // Initialise
    if (actions) {
      Define(actions);
    }

    // ----------------------
    // PUBLIC: Return actions
    // ----------------------
    function Actions() {
      return mActions;
    }

    // ----------------------
    // PUBLIC: Define Actions
    // ----------------------
    function Define(actions) {
      mActions = actions;

      // Normalise actions (i.e., ensure they are valid and fill in the missing properties)
      for (var i = 0; i < mActions.length; i++) {
        var a = $.extend({}, ActionDefaults, mActions[i]);
        mActions[i] = a;
      }
    }

    // ------------------------------------------------------------------------------------------
    // PUBLIC: Append additional Actions from a FormHeaderInfo object
    //
    // NOTE:
    // A FormHeaderInfo is returned from Intersoft Web Services, e.g., ISFormClient.GetHeaderInfo
    // ------------------------------------------------------------------------------------------
    function AppendFromFormHeaderInfo(formHeaderInfo) {
      // Check
      if (!formHeaderInfo || !formHeaderInfo.Actions) return;

      for (var i = 0; i < formHeaderInfo.Actions.length; i++) {
        // Create Actions
        // NOTE: Server-side properties are upper-case so we must use these to populate client-side object
        var ssa = formHeaderInfo.Actions[i];
        var a = $.extend({}, ActionDefaults, {});

        a.actionId = ssa.ActionId;
        a.buttonCaption = ssa.ButtonCaption;
        a.caption = ssa.Caption;
        a.alwaysShowCaption = ssa.AlwaysShowCaption;
        a.context = (ssa.ContextPageId ? true : false);
        a.contextPageId = ssa.ContextPageId;
        a.groupId = ssa.GroupId;
        a.icon = ssa.Icon;
        a.repeatInGroupId = ssa.RepeatInGroupId;
        a.system = ssa.System;
        a.applicationShortcutUrl = ssa.ApplicationShortcutUrl;
        if (ssa.ParametersJson) {
          if (a.applicationShortcutUrl) {
            console.warn("$UI.ActionsCollection.AppendFromFormHeaderInfo: Action '" + a.actionId + "' defined both an Application Shortcut URL and JSON Parameters. JSON Parameters were ignored.");
          }
          else {
            try {
              a.data = JSON.parse(ssa.ParametersJson);
            }
            catch (ex) {
              window.alert("$UI.ActionsCollection.AppendFromFormHeaderInfo: Action '" + a.actionId + "'\n\nFailed to parse ParametersJson.\n\n" + ex);
            }
          }
        }

        mActions.push(a);
      }
    }

    // ---------------------
    // PUBLIC: Get an action
    // ---------------------
    function GetAction(actionId) {
      actionId = actionId.toUpperCase();

      for (var i = 0; i < mActions.length; i++) {
        var a = mActions[i];
        if (a.actionId.toUpperCase() == actionId) {
          return a;
        }
      }

      return null;
    }

    // ---------------------------------------------------------
    // PUBLIC: Get the applicationShortcutUrl property of action
    // ---------------------------------------------------------
    function GetApplicationShortcutUrl(actionId) {
      var a;

      actionId = actionId.toUpperCase();

      for (var i = 0; i < mActions.length; i++) {
        a = mActions[i];
        if (a.actionId && a.actionId.toUpperCase() == actionId) {
          return a.applicationShortcutUrl;
        }
      }

      return false;
    }

    // --------------------------------------
    // PUBLIC: Get checked property of action
    // --------------------------------------
    function GetChecked(actionId) {
      var a;

      actionId = actionId.toUpperCase();

      for (var i = 0; i < mActions.length; i++) {
        a = mActions[i];
        if (a.actionId && a.actionId.toUpperCase() == actionId) {
          return a.checked;
        }
      }

      return false;
    }

    // --------------------------------------
    // PUBLIC: Set checked property of action
    // --------------------------------------
    function SetChecked(actionId, checked) {
      var a;

      actionId = actionId.toUpperCase();
      checked = checked ? true : false;

      for (var i = 0; i < mActions.length; i++) {
        a = mActions[i];
        if (a.actionId && a.actionId.toUpperCase() == actionId) {
          a.checked = checked;
        }
      }
    }

    // --------------------------------------
    // PUBLIC: Set enabled property of action
    // --------------------------------------
    function SetEnabled(actionId, enabled, tooltipText) {
      var a;

      actionId = actionId.toUpperCase();

      for (var i = 0; i < mActions.length; i++) {
        a = mActions[i];
        if (a.actionId && a.actionId.toUpperCase() == actionId) {
          a.enabled = enabled;
          if (tooltipText != undefined) a.tooltipText = tooltipText;
        }
      }
    }

    // --------------------------------------
    // PUBLIC: Get enabled property of action
    // --------------------------------------
    function GetEnabled(actionId) {
      var a;

      actionId = actionId.toUpperCase();

      for (var i = 0; i < mActions.length; i++) {
        a = mActions[i];
        if (a.actionId && a.actionId.toUpperCase() == actionId) {
          return a.enabled;
        }
      }

      return false;
    }

    // --------------------------------------
    // PUBLIC: Set visible property of action
    // --------------------------------------
    function SetVisible(actionId, visible) {
      var a;

      actionId = actionId.toUpperCase();

      for (var i = 0; i < mActions.length; i++) {
        a = mActions[i];
        if (a.actionId && a.actionId.toUpperCase() == actionId) {
          a.visible = visible;
        }
      }
    }

    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    return {
      TypeName: "ActionCollection",

      Actions: Actions,
      Define: Define,
      AppendFromFormHeaderInfo: AppendFromFormHeaderInfo,

      GetAction: GetAction,
      GetApplicationShortcutUrl: GetApplicationShortcutUrl,
      GetEnabled: GetEnabled,

      GetChecked: GetChecked,
      SetChecked: SetChecked,
      SetEnabled: SetEnabled,
      SetVisible: SetVisible
    };
  }


  // ====================================================================================
  // Private: Popup Menu Panel object which can be used to display a Menu Items collection
  // ====================================================================================
  function MenuPopup(parentElement, options) {

    var mElement;
    var mItems = [];
    var mOptions;
    var mOverlayElement = null;
    var mParentElement;
    var mVisible = false;
    var mWatchTimer = null;

    // Extend options with defaults
    MenuPopupDefaults = {
      onAction: null,

      caption: "",

      autoClose: true,
      showCaption: false,
      showCloseButton: false,
      onClose: null,

      forceOverlay: true
    };
    mOptions = $.extend({}, MenuPopupDefaults, options);

    // Initialise
    if (Runtime_IsPlatformIOS) mOptions.forceOverlay = true; // iOS does not handle the contextmenu event in the same way

    // Create Popup Element
    mParentElement = parentElement;
    mElement = $("<div style='display:none; position:fixed; min-width:200px; top:0; left:0;' class='is-popup-menu'></div>");

    // Handle events
    mElement.on("contextmenu", function () { return false; }); // NOTE: This just disables the standard context menu and does not need to use $UI.HandleContextMenuEvent
    if (!mOptions.forceOverlay) {
      mElement.on("mousedownoutside focusoutside selectoutside keydownoutside", function () { Hide(); });
    }

    // -------------------------
    // PUBLIC: Define Menu Items
    // -------------------------
    function Define(items) {
      mItems = items;

      // Normalise items (i.e., ensure they are valid and fill in the missing properties)
      Define_Normalise(mItems);
    }

    // ------------
    // PUBLIC: Show
    // ------------
    function Show(x, y) {
      if (!mVisible) {
        mVisible = true;

        // Position
        if (x != undefined) {
          // Specified position
          mElement.css({ left: x, top: y });
        }
        else {
          // Parent element's position
          var pos = mParentElement.offset();
          mElement.css({ left: pos.left, top: pos.top });
        }

        // Refresh
        if (mItems) Refresh(mElement, mOptions, mItems);

        // iOS does not handle the contextmenu event in the same way so add a (really faint) overlay to prevent elements being clicked underneath
        if (mOptions.forceOverlay) {
          if (!mOverlayElement) {
            mOverlayElement = $("<div class='is-modal-overlay top' style='background-color:rgba(0,0,0,0.2); position: fixed; left:0; right:0; top:0; bottom:0; min-width:100%; min-height:100%;' tabindex='-1'></div>");
            $("body").append(mOverlayElement);
            $("body").on("keydown.contextmenu", function (e) {
              switch (e.keyCode) {
                case 27: // Escape
                  Hide();
                  break;
              }
            });
          }
          mOverlayElement.mousedown(Hide);
        }

        // Show
        mElement.removeClass("active");
        $("body").append(mElement);
        mElement.show();
        var ti = window.setTimeout(function () {
          window.clearTimeout(ti);
          ti = null;

          mElement.addClass("active");
        }, 10);

        if (mOptions.forceOverlay) {
          // iOS does not handle the contextmenu event in the same way
          mOverlayElement.focus();
        }
        else {
          // Handle so we can auto-close when popuped up in an iframe
          // NOTE: Currently we always force the overlay so this code is never used
          if (mWatchTimer) {
            window.clearInterval(mWatchTimer);
            mWatchTimer = null;
          }
          if (document.activeElement && document.activeElement.tagName == "IFRAME") {
            if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
              // Cannot currently get to work in Firefox
            }
            else {
              document.activeElement.blur();
              mElement[0].focus();

              mWatchTimer = window.setInterval(function () {
                if (document.activeElement && document.activeElement.tagName == "IFRAME") {
                  Hide();
                }
              }, 250);
            }
          }
        }

        // Tweak if off right-hand/ bottom of screen
        var dw = $(document).innerWidth();
        var mp = mElement.offset();
        var mw = mElement.innerWidth();
        if (mp.left + mw > dw - 4) {
          var x = dw - mw - 4;
          mElement.css("left", x);
        }
      }
    }

    // ------------
    // PUBLIC: Hide
    // ------------
    function Hide() {
      mElement.remove();

      if (mWatchTimer) {
        window.clearInterval(mWatchTimer);
        mWatchTimer = null;
      }

      if (mVisible) {
        mVisible = false;
        mElement.hide();
      }

      if (mOverlayElement) {
        $("body").off("keydown.contextmenu");
        mOverlayElement.remove();
        mOverlayElement = null;
      }

      // Notify
      if (mOptions.onClose) mOptions.onClose();
    }

    // ------------------------------------------
    // PRIVATE: Refresh (i.e., recreate elements)
    // ------------------------------------------
    function Refresh() {
      var e;

      // Clear existing
      mElement.children().remove();

      // Container
      var ec = $("<div></div>");

      // Caption and Close button
      if (mOptions.caption || mOptions.showCloseButton) {
        var caption = $("<div class='caption is-no-select'></div>");
        caption.text(mOptions.caption);
        if (mOptions.showCloseButton) {
          var closeButton = $("<a><span class='is-symbol-close'></span></a>");
          closeButton.click(function () {
            if (mOptions.onClose) {
              // Call the 'onClose' handler. This may want to do something special
              mOptions.onClose();
            }
            else {
              // Hide the menu element
              Hide();
            }
          });
          caption.append(closeButton);
        }
        mElement.append(caption);

        // Add a special class to container so it knows it has a caption
        ec.addClass("hascaption");
      }

      // Refresh Items
      e = Refresh_Items(mOptions, mItems, false);
      ec.append(e);

      // Finalise
      mElement.append(ec);
    }
    function Refresh_Items(mOptions, items, submenu) {
      var ul, item, li, lib, sub;

      // Outer element
      ul = $("<ul class='is-no-select'></ul>");

      // Items
      for (var i = 0; i < items.length; i++) {
        // Initialise
        item = items[i];

        li = $("<li itemtype='" + item.ItemType + "'></li>");
        lib = $("<a></a>");
        li.attr("itemid", item.ItemId);
        lib.text(item.Caption);
        li.append(lib);

        // Icon
        if (item.Icon) {
          // Resource (set IconUrl)
          item.IconUrl = widget.GetIconUrl(item.Icon);
        }
        if (item.IconUrl) {
          // URL
          var ie = "<img src='" + item.IconUrl + "' />";
          lib.prepend(ie);
        }
        else if (item.IconClass) {
          // CSS Class
          var die = "<div class='is-menu-item-glyph " + item.IconClass + "'></div>";
          lib.prepend(die);
        }

        // Enabled and visibility
        if (!item.Visible) li.css("display", "none");
        li.attr("Enabled", '' + item.Enabled);

        // Append main item
        ul.append(li);

        // Sub items?
        if (item.MenuItems && item.MenuItems.length != 0) {
          // Recurse
          sub = Refresh_Items(mOptions, item.MenuItems, true);

          // Identify as sub-menu
          li.addClass("is-menu-sub");

          // Add into parent menu
          li.append(sub);
        }
        else {
          // Handler
          (function (item) {
            lib.click(function () {
              if (!item.Action && !item.ItemId) {
                // Blank item such as "(no actions available for this row)"
                Hide();
              }
              else if ((item.Action || item.ItemId) && item.Enabled) {
                // Hide Menu
                Hide();

                // Action
                if (mOptions.onAction) {
                  mOptions.onAction(item.Action || item.ItemId, item.ItemId);
                }
                else {
                  window.alert("No onAction handler specified for this menu.");
                }
              }
            });
          })(item);
        }
      }
      return ul;
    }

    // ------------------------
    // PUBLIC: Caption property
    // ------------------------
    function Caption(value) {
      if (value === undefined) {
        // Get
        return mOptions.caption;
      }
      else {
        // Set
        // NOTE: Refresh must be called for the caption to be regenerated
        mOptions.caption = value;
      }
    }

    // --------------------------------
    // PUBLIC: Set the OnAction handler
    // --------------------------------
    function OnAction(handler) {
      mOptions.onAction = handler;
    }

    // ------------------------
    // PUBLIC: Focus Popup Menu
    // ------------------------
    function Focus() {
      mElement.focus();
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    return {
      TypeName: "MenuPopup",

      Caption: Caption,

      Items: mItems,
      Define: Define,

      Show: Show,
      Hide: Hide,
      Focus: Focus,

      OnAction: OnAction
    };
  }


  // ====================
  // PUBLIC: Modal object
  // ====================
  function Modal(options) {

    var mActions;
    var mActionsElement;
    var mCloseElement;
    var mContentElement;
    var mDialogButtonsElement;
    var mFooterElement;
    var mHeaderElement;
    var mModalElement;
    var mModalIndex;
    var mModalId;
    var mTitleElement;
    var mTitleIconElement;
    var mMinimiseElement;
    var mOpenElement;
    var mOptions;
    var mOtherButtonsElement;
    var mOverlayElement;
    var mSourceElement;
    var mSourceElementOriginalParent;
    var mTag = {};
    var mVisible = false;
    var mWaitOverlayElement;
    var mWidget = null;
    var mWidgetDisabledCloseButton = false;

    // Extend options with defaults
    ModalDefaults = {
      formKey: "",
      formType: "", // e.g., HTMLViewer
      dialogResult: "Cancel",

      content: "",

      title: "",
      titleIcon: "",

      width: "50%",
      height: "50%",

      minWidth: 620,          // Only used if width is a percentage
      minHeight: 460,         // Only used if height is a percentage
      maxWidth: "",           // Only used if width is a percentage
      maxHeight: "",          // Only used if height is a percentage
      forceWindowed: true,    // If true, this modal will never be full-screened (as of 22/12/2015, I made this the default since it just looks better on mobile devices)

      showClose: true,
      deleteOnClose: true,
      closeOnEscape: false,

      actionCaption: "",

      onAction: null,
      onActionNotification: null,
      onChildClosed: null,
      onClose: null,
      onRefresh: null,
      onResize: null,

      onAfterClose: null,   // Internal use only,

      appShortcutUrl: "",   // If specified, will provide an "Open in new Window" button
      parentModal: null,    // Generally used for a modal opened from a non-modal, e.g., the Web Subscriber form from the Web Subscribers List form
      allowMinimise: false, // Allow minimise onto parent non-modal so User can look around
    };
    mOptions = $.extend({}, ModalDefaults, options);

    // Show Defaults
    ModalShowDefaults = {
      animate: true,
      content: null,
      contentSourceElement: null,
      title: null
    };

    // Initialise
    mModalId = "MODAL" + CreateGuid(true) + "ENDMODAL";
    mActions = new ActionsCollection();

    // --------------------------
    // PUBLIC: Actions collection
    // --------------------------
    function Actions() {
      return mActions;
    }

    // ---------------------------------------------
    // PUBLIC: Close this Modal and remove resources
    // ---------------------------------------------
    function Close() {
      // Remove from stack
      CloseBegin();

      // Remove Elements
      CloseFinalise();
    }

    // --------------------
    // PRIVATE: Begin Close
    // --------------------
    function CloseBegin() {
      // Remove from stack
      if (_self == mModalStack[mModalStack.length - 1]) {
        // Decrement counter (so warnings do not appear about records being opened in the background, even if modals are closing)
        if (mModalOpenCount > 0) mModalOpenCount -= 1;

        // Remove
        var child = mModalStack.pop();

        // Notify parent Modal/ Non-Modal that a child modal has closed
        if (mModalStack.length > 0) {
          // Modal
          if (mModalStack[mModalStack.length - 1].NotifyChildClosed(child));
        }
        else {
          if (_self.ParentModal() && _self.ParentModal().NotifyChildClosed) {
            _self.ParentModal().NotifyChildClosed(child);
          }
        }
      }
      else {
        window.alert("userinterface.Modal.Close: Could not remove modal from stack since it is not the top-most item. Modals should always be closed last to first.");
      }
    }

    // -----------------------
    // PRIVATE: Finalise Close
    // -----------------------
    function CloseFinalise() {
      if (mOverlayElement) {
        // Restore Source Content Element
        if (mSourceElementOriginalParent) {
          mSourceElement.detach();
          mSourceElement.hide();
          mSourceElementOriginalParent.append(mSourceElement);

          mSourceElement = null;
          mSourceElementOriginalParent = null;
        }

        // Remove elements
        mModalElement.remove();
        mModalElement = null;
        mOverlayElement.remove();
        mOverlayElement = null;

        // Remove events
        $(window).unbind("resize.modal" + mModalIndex);

        // Remove class from body?
        if (mModalOpenCount <= 0) $("body").removeClass("is-has-modal");
      }
      else {
        // Never shown
      }

      // Notify
      if (mOptions.onAfterClose) mOptions.onAfterClose();
    }

    // ----------------------------------
    // PUBLIC: The jQuery Content Element
    // ----------------------------------
    function ContentElement() {
      return mContentElement;
    }

    // -----------------------------
    // PUBLIC: DialogResult property
    // -----------------------------
    function DialogResult(value) {
      if (value === undefined) {
        // Get
        return mOptions.dialogResult;
      }
      else {
        // Set
        mOptions.dialogResult = value;
      }
    }

    // --------------------------------------------------------------------
    // PUBLIC: Get an Element that has been rendered as part of the content
    // --------------------------------------------------------------------
    function GetElement(id) {
      return $("#" + mModalId + id);
    }

    // -----------------------
    // PUBLIC: Hide this Modal
    // -----------------------
    function Hide(close) {
      if (mVisible) {
        // Hide
        mVisible = false;
        mOverlayElement.fadeOut(100);
        if (close) {
          CloseBegin();
          mModalElement.fadeOut(100, function () { CloseFinalise(); });
        }
        else {
          mModalElement.fadeOut(100);
        }
      }
      else if (close) {
        // Close
        Close();
      }
    }

    // -------------------------
    // PUBLIC: Execute an Action
    // -------------------------
    function ExecuteAction(actionId, data) {
      // Try global form action handler first
      var handled = false;
      //if ($App && $App.ExecuteGlobalFormAction) {
      //  handled = $App.ExecuteGlobalFormAction(actionId, data, _self);
      //}

      // Modal action handler
      if (!handled) {
        if (mOptions.onAction) {
          mOptions.onAction(actionId, data);
        }
        else {
          console.warn("widget.UI.Modal.ExecuteAction: No OnAction defined for this Modal object to handle action '" + actionId + "'.");
        }
      }
    }

    // -------------------------------------
    // PUBLIC: Execute a Notification Action
    // -------------------------------------
    function ExecuteNotificationAction(actionId, data) {
      if (mOptions.onActionNotification) {
        mOptions.onActionNotification(actionId, data);
      }
    }

    // ----------------------------
    // PUBLIC: Disable Form Content
    // ----------------------------
    function FormDisable() {
      // Disable and set a special attribute (used in FormEnable)
      var el = $("a, button, input, select, textarea", mModalElement);
      for (var i = 0; i < el.length; i++) {
        e = $(el[i]);
        if (!e.attr("disabled")) {
          if (e.attr("autoreadonly") == undefined || e.attr("autoreadonly") != "false") {
            e.attr("ISFormDisabled", true);
            e.attr("disabled", true);
          }
        }
      }
    }

    // ---------------------------
    // PUBLIC: Enable Form Content
    // ---------------------------
    function FormEnable() {
      // Enable and remove special attribute (set in FormDisable)
      var el = $("a, button, input, select, textarea", mModalElement);
      for (var i = 0; i < el.length; i++) {
        e = $(el[i]);
        if (e.attr("ISFormDisabled")) {
          e.removeAttr("ISFormDisabled");
          e.attr("disabled", false);
        }
      }
    }

    // ------------------------
    // PUBLIC: FormKey property
    // ------------------------
    function FormKey(value) {
      if (value === undefined) {
        // Get
        return mOptions.formKey;
      }
      else {
        // Set
        mOptions.formKey = value;
      }
    }

    // -------------------------
    // PUBLIC: FormType property
    // -------------------------
    function FormType(value) {
      if (value === undefined) {
        // Get
        return mOptions.formType;
      }
      else {
        // Set
        mOptions.formType = value;
      }
    }

    // -------------------------------------------------
    // PUBLIC: Notify that a child Modal has been closed
    // -------------------------------------------------
    function NotifyChildClosed(childModal) {
      if (mOptions.onChildClosed) {
        mOptions.onChildClosed({ child: childModal });
      }
    }

    // -----------------------------------------------------------------
    // PUBLIC: Call the 'onRefresh' method or fallback Refresh mechanism
    // -----------------------------------------------------------------
    function NotifyRefresh() {
      if (mOptions.onRefresh) {
        // Callback
        mOptions.onRefresh();
      }
      else if (mOptions.appShortcutUrl && $App) {
        // Close and re-run Application Shortcut
        Close();
        $Ash.ExecuteUrl(mOptions.appShortcutUrl);
      }
    }

    // -------------------------------------
    // PUBLIC: Get/ Set the OnAction handler
    // -------------------------------------
    function OnAction(handler) {
      if (handler === undefined) {
        // Get
        return mOptions.onAction;
      }
      else {
        // Set
        mOptions.onAction = handler;
      }
    }

    // --------------------------------------------
    // PUBLIC: Set the OnActionNotification handler
    // --------------------------------------------
    function OnActionNotification(handler) {
      mOptions.onActionNotification = handler;
    }

    // -------------------------------------
    // PUBLIC: Set the OnChildClosed handler
    // -------------------------------------
    function OnChildClosed(handler) {
      mOptions.onChildClosed = handler;
    }

    // -------------------------------
    // PUBLIC: Set the OnClose handler
    // -------------------------------
    function OnClose(handler) {
      mOptions.onClose = handler;
    }

    // ---------------------------------
    // PUBLIC: Set the OnRefresh handler
    // ---------------------------------
    function OnRefresh(handler) {
      mOptions.onRefresh = handler;
    }

    // --------------------------------
    // PUBLIC: Set the OnResize handler
    // --------------------------------
    function OnResize(handler) {
      mOptions.onResize = handler;
    }

    // ------------------------------------------
    // PUBLIC: Other Buttons (ActionsCollection)
    // ------------------------------------------
    function OtherButtons() {
      return mOtherButtons;
    }

    // -------------------------------------------------------------------------
    // PUBLIC: Parent Modal (generally used for a modal opened from a non-modal)
    // -------------------------------------------------------------------------
    function ParentModal(value) {
      if (value === undefined) {
        // Get
        return mOptions.parentModal;
      }
      else {
        // Set
        mOptions.parentModal = modal;
      }
    }

    // --------------------------------------------------------------------------------
    // PUBLIC: Load a Portal Page (providing this is being called from within a Portal)
    // --------------------------------------------------------------------------------
    function LoadPortalPage(pageId, parameters) {
      // Check we are running from a Portal
      if (!window._portalInfo) {
        window.alert("You cannot use Modal.LoadPortalPage when running from an HTML Widget rather than a Portal.");
        return;
      }

      // Build URL
      var url = pageId;
      if (parameters) {
        var params = "";
        for (var k in parameters) {
          if (params) params += "&";
          params += encodeURIComponent(k) + "=" + encodeURIComponent(parameters[k]);
        }
        if (params) url += "?" + params;
      }

      // Add IFRAME to Modal
      var name = "IFRAME_" + mModalId; // Name this way so we can identify this iframe's parent Modal
      var iframe = $("<iframe style='position:absolute; left:0; right:0; top:0; bottom:0; width:100%; height:100%; border:none;' border='no' name='" + name + "' id='" + name + "'></frame>");
      mContentElement.append(iframe);

      // If running from within finPOWER Connect Desktop then hide this modal immediately (will be closed further down)
      if (_portalInfo.hostingContext == "HtmlViewer" && !_portalInfo.testingInExternalWebBrowser) {
        _self.Hide(false);
      }

      // Navigate
      portal.Navigate(url, iframe, _self);

      // If running from within finPOWER Connect Desktop then close this modal immediately since an IFRAME cannot be used due to security issues so we open a proper form (modally)
      if (_portalInfo.hostingContext == "HtmlViewer" && !_portalInfo.testingInExternalWebBrowser) {
        _self.Close();
      }
    }

    // ----------------------------------------------------------------------------
    // PUBLIC: Render a View (prefixes all element ids with ModalId to make unique)
    // ----------------------------------------------------------------------------
    function RenderView(templateHtml, updateIds) {
      if (updateIds === undefined) updateIds = true;

      if (updateIds) {
        // Prefix all element Ids
        templateHtml = templateHtml.replace(/ id=\"/g, " id=\"" + mModalId); // Double quotes
        templateHtml = templateHtml.replace(/ id=\'/g, " id=\'" + mModalId); // Single quotes

        // Prefix all For Ids (i.e., Labels linking to Input controls)
        templateHtml = templateHtml.replace(/ for=\"/g, " for=\"" + mModalId);  // Double quotes
        templateHtml = templateHtml.replace(/ for=\'/g, " for=\'" + mModalId);  // Single quotes
      }

      // Set HTML
      mContentElement.html(templateHtml);

      // Re-center?
      if (mOptions.width == "auto" || mOptions.height == "auto") {
        Center();
      }
    }

    // ------------------------------------------------
    // PUBLIC: Set the Element to display in the Footer
    // ------------------------------------------------
    function SetFooterElement(e) {
      if (!mFooterElement) {
        window.alert("userinterface.Modal.SetFooterElement: Cannot set until form has been shown.");
      }
      else {
        if (typeof e == "string") e = $("#" + e);
        e.detach();
        mFooterElement.append(e);
        mFooterElement.show();
      }
    }

    // ------------------------------------------------
    // PUBLIC: Set the Element to display in the Header
    // ------------------------------------------------
    function SetHeaderElement(e) {
      if (!mHeaderElement) {
        window.alert("userinterface.Modal.SetHeaderElement: Cannot set until form has been shown.");
      }
      else {
        if (typeof e == "string") e = $("#" + e);
        e.detach();
        mHeaderElement.append(e);
        mHeaderElement.show();
      }
    }

    // -----------------------
    // PUBLIC: Show this Modal
    // -----------------------
    function Show(options) {
      // Extend options with defaults
      var o = $.extend({}, ModalShowDefaults, options);

      // Update Modal options
      if (o.title) mOptions.title = o.title;
      if (o.titleIcon) mOptions.titleIcon = o.titleIcon;

      // Create elements if necessary
      if (mOverlayElement) {
        if (o.animate) mModalElement.addClass("showing");
      }
      else {
        // Up global counter
        mModalCount += 1;
        mModalIndex = mModalCount;

        // Overlay
        mOverlayElement = $("<div class='is-modal-overlay' style='display:none'></div>");
        mOverlayElement.css("z-index", 2 + (mModalIndex - 1) * 11);
        if (mOptions.allowMinimise) mOverlayElement.addClass("allows-minimise");
        $("body").append(mOverlayElement);

        // Create Elements
        mModalElement = $("<div id='" + mModalId + "' class='is-modal' style='display:none'><div class='is-modal-title-buttons'><div class='is-modal-minimise is-symbol-minimise-window' title='Temporarily minimise this form to view information underneath'></div><div class='is-modal-open-window is-symbol-open-window' title='Open in a new Web Browser Tab\n\nThis provides a URL that can be bookmarked in your browser or sent to someone'></div><div class='is-modal-close is-symbol-close' title='Close'></div></div><div class='is-form-actions-menu' style='display:none'></div><div class='is-modal-title-icon is-no-select'></div><div class='is-modal-title is-no-select'></div><div class='is-modal-header' style='display:none'></div><div class='is-modal-body'></div><div class='is-modal-footer' style='display:none'><ul class='is-modal-dialog-buttons main' style='display:none'></ul><ul class='is-modal-dialog-buttons other' style='display:none'></ul></div></div></div>");
        if (o.animate) mModalElement.addClass("showing");
        $("body").append(mModalElement);
        mModalElement.css("z-index", 10 + (mModalIndex - 1) * 11);
        mMinimiseElement = $(".is-modal-minimise", mModalElement);
        mOpenElement = $(".is-modal-open-window", mModalElement);
        mCloseElement = $(".is-modal-close", mModalElement);
        mTitleIconElement = $(".is-modal-title-icon", mModalElement);
        mTitleElement = $(".is-modal-title", mModalElement);
        mHeaderElement = $(".is-modal-header", mModalElement);
        mContentElement = $(".is-modal-body", mModalElement);
        mFooterElement = $(".is-modal-footer", mModalElement);
        mDialogButtonsElement = $(".main", mModalElement);
        mOtherButtonsElement = $(".other", mModalElement);
        mActionsElement = $(".is-form-actions-menu", mModalElement);

        // Minimise button
        mMinimiseElement.click(function (e) {
          e.preventDefault();
          $UI.ModalMinimise(_self, mOptions.parentModal);
        });

        // Open in new Window button
        mOpenElement.click(function (e) {
          e.preventDefault();
          if ($App) {
            $App.RunAppShortcutInNewBrowserWindow(mOptions.appShortcutUrl);
          }
        });

        // Close button
        mCloseElement.click(function (e) {
          e.preventDefault();
          if (mOptions.onClose) {
            mOptions.onClose();
          }
          else {
            if (mWidgetDisabledCloseButton) {
              // Send a "FormClose" notification to the Widget
              mWidget.ActionNotificationSend("FormClose");
            }
            else {
              Hide(mOptions.deleteOnClose);
            }
          }
        });

        // Keep centered
        $(window).bind("resize.modal" + mModalIndex, function () {
          Center();
          if (mOptions.onResize) mOptions.onResize();
        });

        //// Allow Swipe Left and Right navigation (e.g., for wizards)
        //if ($Runtime.IsMobileBrowser()) {
        //  window.alert("touch swipe enabled for modal");
        //  $(mModalElement).swipe({
        //    swipe: function (event, direction, distance, duration, fingerCount) {
        //      window.alert("swiped: direction=" + direction + ", distance=" + distance + ", duration=" + duration);
        //    }
        //  });
        //}
      }

      // Update content
      if (o.content != null) {
        // Set Content HTML
        mContentElement.html(o.content);
      }
      else if (o.contentSourceElement) {
        // Get Source Element
        if (typeof o.contentSourceElement == "string") {
          o.contentSourceElement = $("#" + o.contentSourceElement);
        }

        // Record source element's original parent
        mSourceElement = o.contentSourceElement;
        mSourceElementOriginalParent = o.contentSourceElement.parent();

        // Move element to Modal (preserving event handlers)
        var e = o.contentSourceElement.detach();
        mContentElement.append(e);
        e.show();
      }

      // Update title
      Title(mOptions.title);

      // Minimise button
      if (mOptions.allowMinimise) {
        mMinimiseElement.show();
        mModalElement.addClass("allows-minimise");
      }
      else {
        mMinimiseElement.hide();
        mModalElement.removeClass("allows-minimise");
      }

      // Open in new Window button
      if (mOptions.appShortcutUrl) {
        mOpenElement.show();
      }
      else {
        mOpenElement.hide();
      }

      // Close button
      if (mOptions.showClose) {
        mCloseElement.show();
      }
      else {
        mCloseElement.hide();
      }

      // Center
      Center();

      // Show
      mVisible = true;
      mOverlayElement.css({ display: "" });
      mModalElement.show();

      // Remove 'showing' class used for animations
      var ti = window.setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        mModalElement.removeClass("showing");
      }, 50);

      //mModalElement.fadeIn(100);

      // Refresh
      Refresh();

      // Updated open count
      mModalOpenCount += 1;

      // Add class to body?
      if (mModalOpenCount == 1) $("body").addClass("is-has-modal");

      // Focus action button
      if (mOptions.focusActionId) {
        var ti = window.setTimeout(function () {
          window.clearTimeout(ti);
          ti = null;

          FocusActionButton(mOptions.focusActionId);
        }, 10);
      }
    }

    // --------------------------
    // PUBLIC: Show Actions popup
    // --------------------------
    function ShowActions() {
      // Show using shared method (used by Modal and NonModal objects)
      ShowFormActionsMenu(mActionsElement, mActions, ExecuteAction);
    }

    // ----------------------------------------------------
    // Center this Modal (keep it a bit higher than center)
    // ----------------------------------------------------
    function Center() {
      var minHeight = parseInt(mOptions.minHeight);
      var minWidth = parseInt(mOptions.minWidth);

      if (!minHeight) minHeight = 460;
      if (!minWidth) minWidth = 620;

      // Decide whether we should show Full-Screen
      var fullScreen = false;
      if (window.innerWidth <= 640 || window.innerHeight <= 480) {
        // Small window
        fullScreen = true;
      }

      // Set CSS for Centered Window
      if (!fullScreen) {
        // Initialise
        mModalElement.removeClass("is-modal-full");

        // Set Size
        var o = { width: mOptions.width };
        if (mOptions.height == "auto") {
          // Auto-height
        }
        else {
          o.height = mOptions.height;
        }
        mModalElement.css(o);

        // Apply max and min width and height for percentage sizes
        var strTemp = mOptions.width + "";
        if (strTemp && strTemp.substr(strTemp.length - 1, 1) == "%") {
          if (mOptions.minWidth) mModalElement.css({ minWidth: mOptions.minWidth });
          if (mOptions.maxWidth) mModalElement.css({ maxWidth: mOptions.maxWidth });
        }
        var strTemp = mOptions.height + "";
        if (strTemp && strTemp.substr(strTemp.length - 1, 1) == "%") {
          if (mOptions.minHeight) mModalElement.css({ minHeight: mOptions.minHeight });
          if (mOptions.maxHeight) mModalElement.css({ maxHeight: mOptions.maxHeight });
        }
        var h = mModalElement.outerHeight();
        var w = mModalElement.outerWidth();

        var top = Math.max($(window).height() - h, 0) / 3;
        var left = Math.max($(window).width() - w, 0) / 2;

        mModalElement.css({ top: top, left: left });
        //window.alert(mModalElement.attr("style"));

        // Force Full-Screen?
        // NOTE: 20 is a safety adjustment to catch scrollbars
        if (mModalElement.outerWidth() >= window.innerWidth - 20) {
          // Too wide
          fullScreen = true;
        }
        else if (mModalElement.outerHeight() >= window.innerHeight - 20) {
          // Too tall
          fullScreen = true;
        }
      }

      // Set CSS for Full-Screen
      mModalElement.removeClass("forced-windowed");
      if (fullScreen) {
        if (mOptions.forceWindowed) {
          // Force windowed (e.g., from grid preview OR pretty much anywhere since "Full" is barely if ever used)
          mModalElement.css({ top: 8, left: 8, bottom: 8, right: 8, width: "", height: "", minWidth: "", minHeight: "" });
          mModalElement.addClass("forced-windowed");
        }
        else {
          // Full
          mModalElement.addClass("is-modal-full");
          mModalElement.css({ top: 0, left: 0, width: "100%", height: "100%", minWidth: "", minHeight: "" });
        }
      }
    }

    // ------------------------
    // PUBLIC: ModalId property
    // ------------------------
    function ModalId() {
      return mModalId;
    }

    // --------------------------
    // FRIEND: Required for fixes
    // --------------------------
    function ModalElement() {
      return mModalElement;
    }

    // --------------------------------------------
    // PUBLIC: Refresh, e.g., update Dialog Buttons
    // --------------------------------------------
    function Refresh() {
      var footerVisible = false;

      // Check we can refresh
      if (!mOverlayElement) return;

      // Recreate 'Dialog' and 'Other' buttons
      if (Refresh_Buttons("[buttons]", mDialogButtonsElement) > 0) footerVisible = true;
      if (Refresh_Buttons("[buttonsOther]", mOtherButtonsElement) > 0) footerVisible = true;

      // Show footer?
      if (footerVisible) {
        mFooterElement.show();
      }
      else {
        mFooterElement.hide();
      }
    }

    // ------------------------
    // PRIVATE: Refresh buttons
    // ------------------------
    function Refresh_Buttons(groupId, buttonsElement) {
      var countVisible = 0, addActionsButton = false;
      var action, button, e;

      // Clear existing
      buttonsElement.children().remove();

      // Create
      for (var i = 0; i < mActions.Actions().length; i++) {
        // Initialise
        action = mActions.Actions()[i];

        if ((action.groupId.toUpperCase() == groupId.toUpperCase() || (action.repeatInGroupId && action.repeatInGroupId.toUpperCase() == groupId.toUpperCase())) && action.visible) {
          // Track
          countVisible += 1;

          // Add button
          e = $("<li><button class='is-button'></button></li>");
          buttonsElement.append(e);
          button = $("button", e);
          button.attr("action-id", action.actionId);

          // Update
          if (groupId == "[buttonsOther]" && action.icon && mIconResolver) {
            // 'Other' buttons group should show Icon in preference to caption, e.g., "Add Log"
            button.addClass("action-other");
            iconUrl = iconUrl = GetIconUrl(action.icon, 16);
            button.css("background-image", "url(" + iconUrl + ")");
            button.attr("title", action.tooltipText || action.caption);
          }
          else {
            // Normal action
            button.text(action.caption);
            button.attr("title", action.tooltipText);
          }
          if (!action.enabled) button.attr("disabled", "disabled");

          if (action.buttonStyle) {
            button.addClass(action.buttonStyle);
          }
          else {
            // Automatic styles
            switch (action.actionId.toUpperCase()) {
              case "ADD":
                button.addClass("positive");
                break;

              case "CANCEL":
              case "CLOSE":
                button.addClass("cancel");
                break;

              case "CUSTOMISE":
                button.addClass("customise");
                e.addClass("system"); // Float to the left
                button.attr("title", "Customise");
                break;

              case "DELETE":
                button.addClass("danger");
                break;

              case "FINISH":
              case "OK":
              case "SAVE":
                button.addClass("ok");
                break;

              case "REFRESH":
                button.addClass("refresh");
                e.addClass("system"); // Float to the left
                button.attr("title", "Refresh");
                break;

              default:
                button.addClass("normal");
                break;
            }
          }

          // Handler
          if (action.enabled) {
            if (action.handler) {
              // Custom handler
              (function (action) { button.click(function () { action.handler(); }); })(action);
            }
            else {
              // Default handler
              // NOTE: This will also automatically handle Custom Actions that are Application Shortcuts
              (function (action) { button.click(function () { ExecuteAction(action.actionId, action.data ? action.data : action.applicationShortcutUrl); }); })(action);
            }
          }
        }
      }

      // Add special 'Actions' button?
      if (groupId == "[buttonsOther]") {
        for (var i = 0; i < mActions.Actions().length; i++) {
          // Initialise
          action = mActions.Actions()[i];

          if (action.groupId.substr(0, 1) != "[") {
            if (action.visible) {
              addActionsButton = true;
              countVisible += 1;
              break;
            }
          }
        }

        if (addActionsButton) {
          // Add button
          e = $("<li class='system'><button class='is-button actions' title='Actions'></button></li>");
          buttonsElement.append(e);
          button = $("button", e);

          // Default handler
          (function () { button.click(function () { ShowActions(); }); })();
        }
      }

      // Show buttons?
      if (countVisible > 0) {
        buttonsElement.show();
      }
      else {
        buttonsElement.hide();
      }

      return countVisible;
    }

    // ------------------------------------------
    // PUBLIC: Set input focus to a button action
    // ------------------------------------------
    function FocusActionButton(actionId) {
      // Add a slight delay to let browser render buttons if just showing
      var ti = window.setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        var e = $("button[action-id='" + actionId + "']", mModalElement);
        e.focus();
      }, 10);
    }

    // ----------------------
    // PUBLIC: Title property
    // ----------------------
    function Title(value) {
      if (value === undefined) {
        // Get
        return mOptions.title;
      }
      else {
        // Set
        if (value) {
          mTitleElement.text(value);
          mTitleElement.show();
        }
        else {
          mTitleElement.text("");
          mTitleElement.hide();
        }
      }
    }

    // ---------------------------------------------------------
    // PUBLIC: TitleIcon property (an HTML snippet or Icon name)
    // ---------------------------------------------------------
    function TitleIcon(value) {
      if (value === undefined) {
        // Get
        return mOptions.titleIcon;
      }
      else {
        // Set
        if (value) {
          mTitleIconElement.html(value);
          mTitleIconElement.show();
        }
        else {
          mTitleIconElement.text("");
          mTitleIconElement.hide();
        }
      }
    }

    // =========================
    // PUBLIC: Show Wait Overlay
    // =========================
    function WaitShow(message) {
      // Create elements if necessary
      if (!mWaitOverlayElement) {
        // Initialise
        if (!message) message = "";

        // Create
        mWaitOverlayElement = $("<div class='is-modal-overlay top is-wait-block' style='display:none'><div class='is-wait'><div class='is-wait1'></div><div class='is-wait2'></div><div class='is-wait3'></div></div><label>" + HtmlEncode(message) + "</label></div>");
        mModalElement.append(mWaitOverlayElement);

        // Show
        //mWaitOverlayElement.fadeIn(100);
        mWaitOverlayElement.show();
      }
    }

    // ===================================
    // PUBLIC: Update Wait Overlay Message
    // ===================================
    function WaitUpdate(message) {
      // Create elements if necessary
      if (mWaitOverlayElement) {
        $("label", mWaitOverlayElement).text(message);
        mWaitOverlayElement.show();
      }
    }

    // =========================
    // PUBLIC: Hide Wait Overlay
    // =========================
    function WaitHide() {
      if (mWaitOverlayElement) {
        mWaitOverlayElement.remove();
        mWaitOverlayElement = null;
      }
    }

    // ====================================================================
    // FRIEND : HTML Widget has requested that the Close Button be disabled
    // ====================================================================
    function WidgetDisabledCloseButton(widget) {
      mWidgetDisabledCloseButton = true;
      mWidget = widget;
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      TypeName: "Modal",

      Actions: Actions,
      Close: Close,
      ContentElement: ContentElement,
      DialogResult: DialogResult,
      //ExecuteAction: ExecuteAction,
      //ExecuteNotificationAction: ExecuteNotificationAction,
      //FocusActionButton: FocusActionButton,
      FormDisable: FormDisable,
      FormEnable: FormEnable,
      ////FormReadOnly: FormReadOnly,
      //FormKey: FormKey,
      //FormType: FormType,
      GetElement: GetElement,
      Hide: Hide,
      LoadPortalPage: LoadPortalPage,
      ModalId: ModalId,
      ModalElement: ModalElement,
      ParentModal: ParentModal,
      Refresh: Refresh,
      RenderView: RenderView,
      //SetFooterElement: SetFooterElement,
      //SetHeaderElement: SetHeaderElement,
      Show: Show,
      //ShowActions: ShowActions,
      Title: Title,
      //TitleIcon: TitleIcon,

      //HeaderHide: function () { /* Compatibility with non-modal */ },
      //HeaderShow: function () { /* Compatibility with non-modal */ },

      NotifyChildClosed: NotifyChildClosed, // Internal use only
      //NotifyRefresh: NotifyRefresh,

      OnAction: OnAction,
      //OnActionNotification: OnActionNotification,
      //OnChildClosed: OnChildClosed,
      OnClose: OnClose,
      //OnRefresh: OnRefresh,
      OnResize: OnResize,

      WaitShow: WaitShow,
      WaitUpdate: WaitUpdate,
      WaitHide: WaitHide,

      CloseOnEscape: function () { return mOptions.closeOnEscape; },

      Tag: mTag, // Allow values to be attached to this object

      // Friend
      WidgetDisabledCloseButton: WidgetDisabledCloseButton,
    };

    // Add to stack
    mModalStack.push(_self);

    return _self;
  }



  // ===============================
  // PUBLIC: AccountFinancial object
  // ===============================
  function AccountFinancial(e, options) {

    var mAccountCalc;
    var mConfig = {};
    var mCumulativeTotal;
    var mEditStandardTransactionIndex;
    var mElement;
    var mInitialised = false;
    var mOptions;
    var mRecord;
    var mStdTransactionOwnerClientIds;
    var mPayments;
    var mPayments_Edit;
    var mPromises = [];

    // Modal Windows
    var mForm_OverridingPayments;
    var mForm_PaymentSchedule;
    var mForm_PromiseAdd;
    var mForm_TotalInterest;

    var C = {
      // Table layout
      trMain: null,
      tdMain: null,
      tblStdTransactions: null,
      tblTermAndPayments: null,
      tblInterest: null,
      divAdvanced: null,
      tblAdvanced: null,

      // Standard Transactions
      lblStdTransactions: null,
      gridStdTrans: null,

      // Restructure
      lblFinalPayment: null,
      chkHoldToOriginalMaturityDate: null,
      chkHoldFinalPaymentDate: null,
      datePaymentFinalDate: null,
      chkByNumberofPayments: null,
      numNumberofPayments: null,

      // Term & Payments
      lblTerm: null,
      dateOpeningDate: null,
      cboTermCycle: null,
      dateTermCycleOnDate: null,
      dateMaturityDate: null,
      numTermNumberOfPayments: null,

      lblMinimumPayments: null,
      cboMinimumPaymentBasis: null,
      numMinimumPaymentValue: null,
      numMinimumPaymentPercent: null,
      dateMinimumPaymentInstalmentEndDate: null,
      numMinimumPaymentInstalmentResidualValue: null,
      numMinimumPaymentDueDays: null,
      chkMinimumPaymentDueDaysOverride: null,
      cboMinimumPaymentHoldToPeriod: null,
      dateMinimumPaymentHoldToDate: null,

      lblPayments: null,
      cboPaymentCycle: null,
      cboPaymentFirstDatePeriod: null,
      datePaymentFirstDate: null,
      datePaymentNextDate: null,
      numPaymentRegular: null,
      numPaymentBalloon: null,

      lblResidualValue: null,
      numResidualValue: null,

      lblCreditLimit: null,
      numCreditLimit1: null,
      numCreditLimit2: null,
      numCreditLimit3: null,

      lblTaxCategory: null,
      cboTaxCategory: null,

      // Interest
      lblInterest: null,
      cboInterestCycle: null,
      dateInterestCycleDateFirst: null,
      cboInterestPaymentType: null,

      lblStartupInterest: null,
      cboStartupInterestType: null,
      cboStartupInterestPeriod: null,
      dateStartupInterestToDate: null,
      numStartupInterestRate: null,
      cboStartupInterestRateTable: null,
      numStartupInterestRatePremium: null,
      numStartupInterestRateBase: null,

      lblInterestRate: null,
      cboInterestType: null,
      numInterestRate: null,
      cboInterestRateTable: null,
      numInterestRatePremium: null,
      numInterestRateBase: null,

      lblOtherInterest: null,
      numOtherInterestRate: null,

      // Advanced: Default Interest
      lblDefaultInterest: null,
      cboDefaultInterestRateBasis: null,
      numDefaultInterestRate: null,

      // Advanced: Interest Rate change instructions
      lblInterestInstructions: null,
      cboInterestInstructionDown: null,
      cboInterestInstructionUp: null,

      // Advanced: Options
      lblFinancialOptions: null,
      chkPaymentsInAdvance: null,
      chkOptionPaymentsFinalPlusBalloon: null,
      chkOptionInterestOnInterest: null,
      cboOptionPaymentAllocationMethod: null,

      // Buttons
      cmdSchedule: null,
      cmdResetFinancial: null,
      cmdAdvancedOptions: null,

      cmdPromiseAdd: null,
      cmdOverridingPayments: null,
      cmdPaymentSchedule: null,
    };

    var C_TotalInterest = {
      lblTotalInterest: null,
      numTotalInterest: null,
    };

    var C_OverridingPayments = {
      gridPayments: null,
    };

    var C_PaymentSchedule = {
      gridPaymentSchedule: null,
    };

    var C_PromiseAdd = {
      lblPromiseAdd: null,
      chkPromisesClear: null,
      numPromiseTotal: null,
      cboPromiseFrequency: null,
      datePromiseFirst: null,
      numPromiseValue: null,
      numPromiseNumberOfPayments: null,
      divPromiseInformation: null,
    };

    // Extend options with defaults
    AccountFinancialDefaults = {
      readOnly: false,
      allowStdTransDrilldown: true,
      allowStdTransReset: true,
      allowReset: true,
      allowSchedule: true,
      allowPaymentSchedule: true,
      allowAdvanced: true,
      autoReadOnly: true,
      showStdTrans: true,
      stdTransWidgetId: "",
      visible: true,
      advancedVisible: false,
      isRefinance: false,
      isRestructure: false,

      onAction: null,
      onChange: null,
    };
    mOptions = $.extend({}, AccountFinancialDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.AccountFinancial: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Validate Element
    switch (mElement.prop("tagName")) {
      case "TBODY":
        break;

      default:
        console.warn("widget_ui.AccountFinancial: Element '" + id + "' must be a TBODY element.");
        return;
    }

    // Apply class
    mElement.addClass("is-account-financial");

    // Create sub-elements and controls
    //   Main layout tables (3 tables within flex divs)
    C.trMain = $("<tr></tr>");
    mElement.append(C.trMain);
    C.tdMain = $("<td></td>");
    C.trMain.append(C.tdMain);

    if (mOptions.showStdTrans) {
      C.tblStdTransactions = $("<div></div>");
      C.tdMain.append(C.tblStdTransactions);
      C.tblStdTransactions.wrap("<div class='tblStdTransactions'></div>");
    }

    var divNonStdTrans = $("<div class='tblNonStdTransactions'></div>");
    C.tdMain.append(divNonStdTrans);

    C.tblTermAndPayments = $("<table class='is-form'></table>");
    divNonStdTrans.append(C.tblTermAndPayments);
    C.tblTermAndPayments.wrap("<div class='tblTermAndPayments' style='overflow-x:hidden'></div>");
    C.tblTermAndPayments.append("<colgroup><col style='width:8em;'/><col/></colgroup>");

    C.tblInterest = $("<table class='is-form'></table>");
    divNonStdTrans.append(C.tblInterest);
    C.tblInterest.wrap("<div class='tblInterest'></div>");
    C.tblInterest.append("<colgroup><col style='width:8em;'/><col/></colgroup>");

    C.tblAdvanced = $("<table class='is-form'></table>");
    divNonStdTrans.append(C.tblAdvanced);
    C.tblAdvanced.wrap("<div class='tblAdvanced'></div>");
    C.tblAdvanced.append("<colgroup><col style='width:8em;'/><col/></colgroup>");
    C.divAdvanced = C.tblAdvanced.parent();
    if (!mOptions.advancedVisible) C.divAdvanced.hide();

    var tr, cid;

    //   Standard Transactions
    if (mOptions.showStdTrans) {
      cid = CreateGuid(true);

      C.gridStdTrans = Grid(C.tblStdTransactions, {
        showContextMenu: false, // Exporting text values, e.g., "3% of Balance" gets formatted incorrectly
        showColumnHeaders: false,
        stickyHeader: true, // Force buttons below grid to stick
        docked: true,
        width: "100%",

        onAction: function (actionId) {
          switch (actionId) {
            case "Add":
              EditStandardTransaction(-1);
              break;

            case "DeleteRow":
              // Flag as deleted
              mRecord.StdTrans[C.gridStdTrans.ActiveDataRowListIndex()].Deleted = true;

              // Block UI
              Block("Removing Transaction, please wait...");

              // Notify
              OnChange();
              break;

            case "RowMoveDown":
              C.gridStdTrans.RowMoveDown();

              // Notify
              OnChange();
              break;

            case "RowMoveUp":
              C.gridStdTrans.RowMoveUp();

              // Notify
              OnChange();
              break;

            default:
              if (mOptions.onAction) mOptions.onAction(actionId);
          }
        },
        onAfterRowActivate: gridStdTrans_AfterRowActivate,
        onBeforeCellUpdate: gridStdTrans_BeforeCellUpdate,
        onInitialiseRow: gridStdTrans_InitialiseRow,
        onRowDrilldown: gridStdTrans_RowDrilldown,
      });
      if (mOptions.allowStdTransDrilldown) C.gridStdTrans.AddColumnDrilldown("Drilldown");
      C.gridStdTrans.AddColumnString("Description", { caption: "Description", allowEdit: false, width: "60%" });
      C.gridStdTrans.AddColumnCurrency("Value", { caption: "Value", allowEdit: true, width: "40%" });

      var actions = [];
      if (mOptions.allowStdTransDrilldown) {
        actions.push({ actionId: "Add", tooltipText: "Add Transaction", icon: "Add" });
        actions.push({ actionId: "DeleteRow", tooltipText: "Delete row", icon: "Delete" });
        actions.push({});
        actions.push({ actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" });
        actions.push({ actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" });
      }
      if (mOptions.allowStdTransReset && !mOptions.isRestructure) {
        actions.push({});
        actions.push({ actionId: "StdTransReset", tooltipText: "Reset Transactions to Account Type defaults", icon: "Reset" });
      }
      C.gridStdTrans.Actions().Define(actions);
    }

    //   Restructure
    if (mOptions.isRestructure) {
      cid = CreateGuid(true);

      tr = $("<tr><th colspan='2'><label>Final Payment</label></th></tr>");
      C.tblTermAndPayments.append(tr);
      C.lblFinalPayment = Label($("label", tr), {});

      cid += "X";
      tr = $("<tr class='narrow'><th colspan='2'><input id='" + cid + "' type='checkbox' /></th></tr>");
      C.tblTermAndPayments.append(tr);
      C.chkHoldToOriginalMaturityDate = RadioButton($("input", tr), {
        caption: "On original Maturity Date?",
        captionWrap: true,

        onChange: chkHoldToOriginalMaturityDate_Change,
      });

      cid += "X";
      tr = $("<tr class='narrow'><th colspan='2'><input id='" + cid + "' type='checkbox' /></th></tr>");
      C.tblTermAndPayments.append(tr);
      C.chkHoldFinalPaymentDate = RadioButton($("input", tr), {
        caption: "On set date?",
        captionWrap: true,

        onChange: chkHoldFinalPaymentDate_Change,
      });

      cid += "X";
      tr = $("<tr><th class='indent1'><label for='" + cid + "'>Final Date:</label></th><td><input id='" + cid + "'/></td></tr>");
      C.tblTermAndPayments.append(tr);
      C.datePaymentFinalDate = DateBox($("input", tr), {
        allowBlank: false,

        onChange: OnChange,
      });

      cid += "X";
      tr = $("<tr class='narrow'><th colspan='2'><input id='" + cid + "' type='checkbox' /></th></tr>");
      C.tblTermAndPayments.append(tr);
      C.chkByNumberofPayments = RadioButton($("input", tr), {
        caption: "By Number of Payments?",
        captionWrap: true,

        onChange: chkByNumberofPayments_Change,
      });

      cid += "X";
      tr = $("<tr><th class='indent1'><label for='" + cid + "'>Payments:</label></th><td><input id='" + cid + "'/></td></tr>");
      C.tblTermAndPayments.append(tr);
      C.numNumberofPayments = NumberBox($("input", tr), {
        allowBlank: false,
        decimals: 0,

        onChange: OnChange,
      });
    }

    //   Term & Payments
    cid = CreateGuid(true);

    //     Term
    tr = $("<tr><th colspan='2'><label>Term</label></th></tr>");
    C.tblTermAndPayments.append(tr);
    C.lblTerm = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Opening:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.dateOpeningDate = DateBox($("input", tr), {
      allowBlank: false,
      onChange: dateOpeningDate_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Term:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.cboTermCycle = DateCycleComboBox($("input", tr), {
      allowBlank: false,
      isFrequency: false,
      showDescription: false,
      width: "10em",
      onChange: cboTermCycle_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>On Date:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.dateTermCycleOnDate = DateBox($("input", tr), {
      allowBlank: false,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Maturity:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.dateMaturityDate = DateBox($("input", tr), {
      allowBlank: true,
      onChange: dateMaturityDate_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>No.&nbsp;Payments:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numTermNumberOfPayments = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: 0,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    //     Minimum Payments
    tr = $("<tr><th colspan='2'><label>Minimum Payments</label></th></tr>");
    C.tblTermAndPayments.append(tr);
    C.lblMinimumPayments = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Basis:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.cboMinimumPaymentBasis = ComboBox($("input", tr), {
      allowBlank: false,
      width: "12em",
      onChange: cboMinimumPaymentBasis_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Value:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numMinimumPaymentValue = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Percentage:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numMinimumPaymentPercent = NumberBox($("input", tr), {
      allowBlank: true,
      blankIfZero: false,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>End&nbsp;Date:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.dateMinimumPaymentInstalmentEndDate = DateBox($("input", tr), {
      allowBlank: false,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Residual:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numMinimumPaymentInstalmentResidualValue = NumberBox($("input", tr), {
      allowBlank: true,
      blankIfZero: false,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    cid += "X";
    var cid2 = (cid + "X2");
    tr = $("<tr><th><label for='" + cid + "'>Due&nbsp;days:&nbsp;</label></th><td><input id='" + cid + "'/>&nbsp;<input id='" + cid2 + "' type='checkbox'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numMinimumPaymentDueDays = NumberBox($("#" + cid), {
      allowBlank: true,
      blankIfZero: false,
      decimals: 0,
      minValue: 0,
      maxValue: 999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    C.chkMinimumPaymentDueDaysOverride = CheckBox($("#" + cid2), {
      caption: "Override?",
      onChange: chkMinimumPaymentDueDaysOverride_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Hold&nbsp;Period:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.cboMinimumPaymentHoldToPeriod = DateCycleComboBox($("input", tr), {
      allowBlank: false,
      isFrequency: true,
      showDescription: false,
      width: "10em",
      onChange: cboMinimumPaymentHoldToPeriod_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Hold To:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.dateMinimumPaymentHoldToDate = DateBox($("input", tr), {
      allowBlank: false,
      onChange: OnChange,
    });

    //     Payments
    tr = $("<tr><th colspan='2'><label>Payments</label></th></tr>");
    C.tblTermAndPayments.append(tr);
    C.lblPayments = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Payments:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.cboPaymentCycle = DateCycleComboBox($("input", tr), {
      allowBlank: false,
      isFrequency: true,
      showDescription: false,
      width: "10em",
      onChange: cboPaymentCycle_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>First&nbsp;Period:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.cboPaymentFirstDatePeriod = DateCycleComboBox($("input", tr), {
      allowBlank: false,
      isFrequency: false,
      showDescription: false,
      width: "10em",
      onChange: cboPaymentFirstDatePeriod_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>First&nbsp;Date:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.datePaymentFirstDate = DateBox($("input", tr), {
      allowBlank: true,
      onChange: OnChange,
    });

    if (mOptions.isRestructure) {
      cid += "X";
      tr = $("<tr><th><label for='" + cid + "'>Next&nbsp;Date:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
      C.tblTermAndPayments.append(tr);
      C.datePaymentNextDate = DateBox($("input", tr), {
        onChange: OnChange,
      });
    }

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Payment:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numPaymentRegular = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: numPaymentRegular_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Balloon:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numPaymentBalloon = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    //    Payment Buttons
    tr = $("<tr><th colspan='2'></th></tr>");
    C.tblTermAndPayments.append(tr);
    td = $("th", tr);

    if (mOptions.isRestructure) {
      C.cmdPromiseAdd = $("<button class='is-button small full-button' icon='Payment_Promise|Add' title='Add Promise'>Promise</button>");
      td.append(C.cmdPromiseAdd);
      C.cmdPromiseAdd.click(showPromiseAdd);
    }

    C.cmdOverridingPayments = $("<button class='is-button small full-button' icon='Payment_Overridden' title='Overriding Payments'>Overriding</button>");
    td.append(C.cmdOverridingPayments);
    C.cmdOverridingPayments.click(showOverridingPayments);

    // Apply button icons
    ApplyIcons($("*[icon]", td));

    //    Residual Value
    tr = $("<tr><th colspan='2'><label>Residual Value</label></th></tr>");
    C.tblTermAndPayments.append(tr);
    C.lblResidualValue = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Residual:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numResidualValue = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    // Credit Limit
    tr = $("<tr><th colspan='2'><label>Credit Limit</label></th></tr>");
    C.tblTermAndPayments.append(tr);
    C.lblCreditLimit = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Credit Limit 1:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numCreditLimit1 = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: numCreditLimit1_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Credit Limit 2:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numCreditLimit2 = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: numCreditLimit2_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Credit Limit 3:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.numCreditLimit3 = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: -1,
      minValue: 0,
      maxValue: 999999999,
      validationMessageBelow: true,
      onChange: numCreditLimit3_Change,
    });

    // Tax Category
    tr = $("<tr><th colspan='2'><label>Tax Category</label></th></tr>");
    C.tblTermAndPayments.append(tr);
    C.lblTaxCategory = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Category:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblTermAndPayments.append(tr);
    C.cboTaxCategory = DBCombo($("input", tr), {
      allowBlank: true,
      width: widget.UI.FIELD_WIDTH_CODE_5,
      onChange: OnChange,
    });

    //   Interest
    cid = CreateGuid(true);

    tr = $("<tr><th colspan='2'><label>Interest</label></th></tr>");
    C.tblInterest.append(tr);
    C.lblInterest = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Cycle:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.cboInterestCycle = DateCycleComboBox($("input", tr), {
      allowBlank: false,
      isFrequency: true,
      showDescription: false,
      width: "10em",
      onChange: cboInterestCycle_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>First Date:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.dateInterestCycleDateFirst = DateBox($("input", tr), {
      allowBlank: true,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Pay Type:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.cboInterestPaymentType = ComboBox($("input", tr), {
      allowBlank: false,
      width: "10em",
      onChange: cboInterestPaymentType_Change,
    });

    //     Startup Interest
    tr = $("<tr><th colspan='2'><label>Startup Interest Rate</label></th></tr>");
    C.tblInterest.append(tr);
    C.lblStartupInterestRate = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Startup&nbsp;Type:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.cboStartupInterestType = ComboBox($("input", tr), {
      allowBlank: false,
      width: "10em",
      onChange: cboStartupInterestType_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Period:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.cboStartupInterestPeriod = DateCycleComboBox($("input", tr), {
      isFrequency: false,
      allowBlank: false,
      showDescription: false,
      width: "10em",
      onChange: cboStartupInterestPeriod_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>To&nbsp;Date:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.dateStartupInterestToDate = DateBox($("input", tr), {
      allowBlank: false,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Interest&nbsp;Rate:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.numStartupInterestRate = NumberBox($("input", tr), {
      allowBlank: false,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,
      onChange: numStartupInterestRate_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Rate Table:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.cboStartupInterestRateTable = DBCombo($("input", tr), {
      allowBlank: false,
      width: widget.UI.FIELD_WIDTH_CODE_10,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>+Premium:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.numStartupInterestRatePremium = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Base:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.numStartupInterestRateBase = NumberBox($("input", tr), {
      allowBlank: true,
      autoReadOnly: false,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      readOnly: true,
    });

    //     Interest Rate
    tr = $("<tr><th colspan='2'><label>Interest Rate</label></th></tr>");
    C.tblInterest.append(tr);
    C.lblInterestRate = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Interest&nbsp;Type:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.cboInterestType = ComboBox($("input", tr), {
      allowBlank: false,
      width: "10em",
      onChange: cboInterestType_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Interest&nbsp;Rate:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.numInterestRate = NumberBox($("input", tr), {
      allowBlank: false,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,

      onButtonClick: numInterestRate_ButtonClick,
      onChange: numInterestRate_Change,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Rate Table:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.cboInterestRateTable = DBCombo($("input", tr), {
      allowBlank: false,
      width: widget.UI.FIELD_WIDTH_CODE_10,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>+Premium:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.numInterestRatePremium = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Base:</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.numInterestRateBase = NumberBox($("input", tr), {
      allowBlank: true,
      autoReadOnly: false,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      readOnly: true,
    });

    //     Other Interest
    tr = $("<tr><th colspan='2'><label>Other Interest</label></th></tr>");
    C.tblInterest.append(tr);
    C.lblOtherInterest = Label($("label", tr), {});

    cid += "X";
    tr = $("<tr><th><label for='" + cid + "'>Other&nbsp;Rate:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblInterest.append(tr);
    C.numOtherInterestRate = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    //     Advanced: Default Interest
    cid = CreateGuid(true);

    tr = $("<tr><th colspan='2'><label>Default Interest</label></th></tr>");
    C.tblAdvanced.append(tr);
    C.lblDefaultInterest = Label($("label", tr), {});

    cid += "A";
    tr = $("<tr><th><label for='" + cid + "'>Rate&nbsp;Basis:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblAdvanced.append(tr);
    C.cboDefaultInterestRateBasis = ComboBox($("input", tr), {
      allowBlank: true,
      width: "10em",
      onChange: OnChange,
    });

    cid += "A";
    tr = $("<tr><th><label for='" + cid + "'>Default&nbsp;Rate:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblAdvanced.append(tr);
    C.numDefaultInterestRate = NumberBox($("input", tr), {
      allowBlank: true,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      validationMessageBelow: true,
      onChange: OnChange,
    });

    tr = $("<tr><th colspan='2'><label>Interest Rate change instructions</label></th></tr>");
    C.tblAdvanced.append(tr);
    C.lblInterestInstructions = Label($("label", tr), {});

    cid += "A";
    tr = $("<tr><th><label for='" + cid + "'>Rate&nbsp;Decrease:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblAdvanced.append(tr);
    C.cboInterestInstructionDown = ComboBox($("input", tr), {
      allowBlank: false,
      width: "10em",
      onChange: OnChange,
    });

    cid += "A";
    tr = $("<tr><th><label for='" + cid + "'>Rate&nbsp;Increase:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblAdvanced.append(tr);
    C.cboInterestInstructionUp = ComboBox($("input", tr), {
      allowBlank: false,
      width: "10em",
      onChange: OnChange,
    });

    tr = $("<tr><th colspan='2'><label>Options</label></th></tr>");
    C.tblAdvanced.append(tr);
    C.lblFinancialOptions = Label($("label", tr), {});

    cid += "A";
    tr = $("<tr><th colspan='2'><input id='" + cid + "' type='checkbox'/></th></tr>");
    C.tblAdvanced.append(tr);
    C.chkPaymentsInAdvance = CheckBox($("input", tr), {
      caption: "Payments in Advance?",
      onChange: OnChange,
    });

    cid += "A";
    tr = $("<tr><th colspan='2'><input id='" + cid + "' type='checkbox'/></th></tr>");
    C.tblAdvanced.append(tr);
    C.chkOptionPaymentsFinalPlusBalloon = CheckBox($("input", tr), {
      caption: "Include Regular with Balloon Payment?",
      onChange: OnChange,
    });

    cid += "A";
    tr = $("<tr><th colspan='2'><input id='" + cid + "' type='checkbox'/></th></tr>");
    C.tblAdvanced.append(tr);
    C.chkOptionInterestOnInterest = CheckBox($("input", tr), {
      caption: "Interest on Interest?",
      onChange: OnChange,
    });

    cid += "A";
    tr = $("<tr><th><label for='" + cid + "'>Payment&nbsp;Allocation:&nbsp;</label></th><td><input id='" + cid + "'/></td></tr>");
    C.tblAdvanced.append(tr);
    C.cboOptionPaymentAllocationMethod = ComboBox($("input", tr), {
      allowBlank: false,
      width: "14em",
      onChange: OnChange,
    });


    //    Buttons
    if (mOptions.allowAdvanced || mOptions.allowPaymentSchedule || mOptions.allowSchedule || mOptions.allowReset) {
      tr = $("<tr><th colspan='2' style='padding-top:8px'></th></tr>");
      C.tblInterest.append(tr);
      td = $("th", tr);

      if (mOptions.allowSchedule) {
        C.cmdSchedule = $("<button class='is-button small' icon='Schedule'>Schedule</button>");
        td.append(C.cmdSchedule);
        if (mOptions.onAction) { C.cmdSchedule.on("click", function () { mOptions.onAction("ScheduleShow"); }); }
      }

      if (mOptions.allowPaymentSchedule) {
        C.cmdPaymentSchedule = $("<button class='is-button small' icon='PaymentSchedule'>Payments</button>");
        td.append(C.cmdPaymentSchedule);
        C.cmdPaymentSchedule.click(showPaymentSchedule);
      }

      if (mOptions.allowReset) {
        C.cmdResetFinancial = $("<button class='is-button small' icon='Reset'>Reset Financial</button>");
        td.append(C.cmdResetFinancial);
        if (mOptions.onAction) { C.cmdResetFinancial.on("click", function () { mOptions.onAction("Reset"); }); }
      }

      if (mOptions.allowAdvanced) {
        C.cmdAdvanced = $("<button class='is-button small' icon='Gears'>Advanced</button>");
        td.append(C.cmdAdvanced);
        C.cmdAdvanced.on("click", function () {
          mOptions.advancedVisible = !mOptions.advancedVisible;
          if (mOptions.advancedVisible) {
            C.cmdAdvanced.addClass("checked");
            C.divAdvanced.slideDown("fast");

            // Update Charge Interest on Interest controls
            UpdateInterestOnInterestVisibility();
          }
          else {
            C.cmdAdvanced.removeClass("checked");
            C.divAdvanced.slideUp("fast");
          }
        });
      }

      // Apply button icons
      ApplyIcons($("*[icon]", td));
    }

    // Update element
    UpdateElement(false);


    function OnChange(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Notify
      if (mOptions.onChange) {
        if (e && e.fieldUpdated) {
          mOptions.onChange(e.fieldUpdated);
        }
        else {
          mOptions.onChange("");
        }
      }
    }

    function UpdateInterestOnInterestVisibility() {
      // Account Class handling
      switch (mRecord.AccountClass) {
        case "Deposit":
        case "Disbursement":
        case "LoanRC":
          C.lblFinancialOptions.Visible(false);
          C.chkOptionInterestOnInterest.Visible(false);
          break;

        default:
          C.lblFinancialOptions.Visible(mConfig.OptionShowFinancialPageOptionsTab);
          C.chkOptionInterestOnInterest.Visible(mConfig.OptionShowFinancialPageOptionsTab);
          break;
      }
    }

    // ------------
    // gridStdTrans
    // ------------
    function gridStdTrans_InitialiseRow(e) {
      var item = mRecord.StdTrans[e.row.listIndex];

      // Update cells
      e.row.cells.Description.value = item.ElementDescription;
      if (item.ValueBasis == "SetValue") {
        // Reverse Value; this is a Transfer From (rather than to)
        if (item.ValueCurrency && mRecord.AccountClass == "Deposit" && item.ElementType == "Transfer" && item.Cycle == "Opening") {
          e.row.cells.Value.value = item.ValueCurrency * -1;
        }
        else {
          e.row.cells.Value.value = item.ValueCurrency;
        }
      }
      else {
        e.row.cells.Value.value = item.ValueDescription;
      }

      // Editing
      if (item.ValueBasis != "SetValue" || !item.AllowChange || item.Cycle != "Opening") {
        e.row.cells.Value.readOnly = true;
      }
      e.row.cells.Description.readOnly = true; // This column is never editable so colour accordingly

      // Tooltips
      if (item.Cycle != "Opening") {
        e.row.cells.Value.tooltipText = item.CycleDescription;
      }

      // Formatting
      e.row.cells.Description.bold = (item.Cycle == "Opening");
    }

    function gridStdTrans_AfterRowActivate(e) {
      // Refresh Buttons
      gridStdTrans_RefreshButtons();
    }

    function gridStdTrans_RefreshButtons() {
      if (C.gridStdTrans.ActiveDataRowListIndex() == -1) {
        C.gridStdTrans.Actions().SetEnabled("DeleteRow", false);
        C.gridStdTrans.Actions().SetEnabled("RowMoveUp", false);
        C.gridStdTrans.Actions().SetEnabled("RowMoveDown", false);
      }
      else {
        C.gridStdTrans.Actions().SetEnabled("DeleteRow", true);
        C.gridStdTrans.Actions().SetEnabled("RowMoveUp", C.gridStdTrans.ActiveDataRowListIndex() > 0);
        C.gridStdTrans.Actions().SetEnabled("RowMoveDown", C.gridStdTrans.ActiveDataRowListIndex() < mRecord.StdTrans.length - 1);
      }

      C.gridStdTrans.RefreshButtons();
      C.gridStdTrans.Focus();
    }

    function gridStdTrans_BeforeCellUpdate(e) {
      var item = mRecord.StdTrans[e.row.listIndex];

      switch (e.columnKey) {
        case "Value":
          if (item.ValueBasis == "SetValue") {
            if (item.ValueCurrency != e.newValue) {
              if (e.newValue) {
                item.ValueCurrency = e.newValue;
              }
              else {
                // This may return a 'null' which will break deserialisation so force a 0 value to be returned
                item.ValueCurrency = 0;
              }

              // Reverse Value; so this is a Transfer From (rather than to)
              if (mRecord.AccountClass == "Deposit" && item.ElementType == "Transfer" && item.Cycle == "Opening") {
                item.ValueCurrency *= -1;
              }

              // Update JSON object since this gets passed to a different wizard
              var o = JSON.parse(item.Json);
              o.ValueCurrency = item.ValueCurrency;
              item.Json = JSON.stringify(o);

              // Notify
              OnChange();
            }
          }
          else {
            //TODO:
            window.alert("todo:");
          }
          break;
      }

      // Refresh row to update styles
      e.refreshRow = true;
    }

    function gridStdTrans_RowDrilldown(e) {
      EditStandardTransaction(e.row.listIndex);
    }

    function EditStandardTransaction(index) {
      // NOTE: For new records, pass across the AccountTypeId so the Element list can be filtered accordingly
      mEditStandardTransactionIndex = index;
      var json = index == -1 ? "{ AccountTypeId: '" + mRecord.AccountTypeId + "' }" : mRecord.StdTrans[index].Json;

      var params = {
        EditJson: true,
        StandardTransactionJson: json,
        OwnerClientIds: (mStdTransactionOwnerClientIds ? mStdTransactionOwnerClientIds : ""),
      };

      // If this is a Restructure, then an Account Id is known
      if (mOptions.isRestructure && mRecord.AccountId) params.IsRestructure = true;

      // If an Account Id is available, append this (Restructure or editing an existing Quote)
      if (mRecord.AccountId) params.AccountId = mRecord.AccountId;

      // Open Modal HTML Widget
      if (mOptions.stdTransWidgetId) {
        widget.UI.Forms.ShowHtmlWidgetModal(mOptions.stdTransWidgetId, { startupParametersJson: JSON.stringify(params) }, NewStdTran_Notify);
      }
      else {
        widget.UI.Forms.ShowHtmlWidgetModal("HtmlWidget:AccountStandardTransaction", { startupParametersJson: JSON.stringify(params) }, NewStdTran_Notify);
      }
    }

    function NewStdTran_Notify(actionId, data) {
      // Parse
      var dataRaw = data;
      data = JSON.parse(data);

      // Handle
      switch (actionId) {
        case "RecordUpdated":
          // Update underlying data
          var item;
          if (mEditStandardTransactionIndex == -1) {
            // New
            item = { Added: true };
            mRecord.StdTrans.push(item);
          }
          else {
            // Existing
            item = mRecord.StdTrans[mEditStandardTransactionIndex];
          }
          item.Json = dataRaw;
          item.ElementDescription = data.ElementDescription;
          item.ValueCurrency = data.ValueCurrency;
          item.ValueDescription = data.ValueDescription;

          // Refresh Grid
          if (mEditStandardTransactionIndex == -1) {
            C.gridStdTrans.VirtualDataRefresh(mRecord.StdTrans);
            C.gridStdTrans.ActivateLastDataRow();
          }
          else {
            C.gridStdTrans.RefreshRow(mEditStandardTransactionIndex);
          }

          // Notify
          OnChange();
          break;
      }
    }

    // --------------------------
    // Non-standard Change events
    // --------------------------
    function numCreditLimit1_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "CreditLimit1" });
    }

    function numCreditLimit2_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "CreditLimit2" });
    }

    function numCreditLimit3_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "CreditLimit3" });
    }

    function cboInterestCycle_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update Controls
      if (C.cboInterestCycle.Text().toUpperCase() == "AT MATURITY") {
        C.dateInterestCycleDateFirst.ReadOnly(false);
      }
      else {
        C.dateInterestCycleDateFirst.ReadOnly(true);
      }

      // Notify
      if (sender) OnChange();
    }

    function cboStartupInterestType_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Used?
      if (!mConfig.OptionAllowStartupInterest) return;

      // Reset if blanked
      if (C.cboStartupInterestType.ListIndex() == -1) C.cboStartupInterestType.Text(mRecord.StartupInterestTypeText);

      // Update Controls
      if (C.cboStartupInterestType.ListIndex() == -1) {
        // Ignore
      }
      else {
        switch (mConfig.StartupInterestTypeList[C.cboStartupInterestType.ListIndex()].Code) {
          case "FixedRate":
            C.cboStartupInterestPeriod.VisibleRow(true);
            C.numStartupInterestRate.VisibleRow(true);
            C.cboStartupInterestRateTable.VisibleRow(false);
            C.numStartupInterestRatePremium.VisibleRow(false);
            C.numStartupInterestRateBase.VisibleRow(false);
            C.dateStartupInterestToDate.VisibleRow(false);
            break;

          case "FloatingRate":
            C.cboStartupInterestPeriod.VisibleRow(true);
            C.numStartupInterestRate.VisibleRow(true);
            C.cboStartupInterestRateTable.VisibleRow(false);
            C.numStartupInterestRatePremium.VisibleRow(true);
            C.numStartupInterestRateBase.VisibleRow(true);
            C.dateStartupInterestToDate.VisibleRow(false);
            break;

          case "InterestFree":
            C.cboStartupInterestPeriod.VisibleRow(true);
            C.numStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestRateTable.VisibleRow(false);
            C.numStartupInterestRatePremium.VisibleRow(false);
            C.numStartupInterestRateBase.VisibleRow(false);
            C.dateStartupInterestToDate.VisibleRow(false);
            break;

          case "NotApplicable":
            C.cboStartupInterestPeriod.VisibleRow(false);
            C.dateStartupInterestToDate.VisibleRow(false);
            C.numStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestRateTable.VisibleRow(false);
            C.numStartupInterestRatePremium.VisibleRow(false);
            C.numStartupInterestRateBase.VisibleRow(false);
            C.dateStartupInterestToDate.VisibleRow(false);
            break;

          case "RateTable":
            C.cboStartupInterestPeriod.VisibleRow(true);
            C.numStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestRateTable.VisibleRow(true);
            C.numStartupInterestRatePremium.VisibleRow(true);
            C.numStartupInterestRateBase.VisibleRow(false);
            break;

          default:
            console.warn("widget_ui.AccountFinancial: Unhandled Startup Interest Type '" + mConfig.StartupInterestTypeList[C.cboStartupInterestType.ListIndex()].Code + "'");
        }
      }

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "StartupInterestType" });
    }

    function chkHoldToOriginalMaturityDate_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Uncheck Others
      if (C.chkHoldToOriginalMaturityDate.Value()) {
        C.chkHoldFinalPaymentDate.Value(false);
        C.chkByNumberofPayments.Value(false);
        chkHoldFinalPaymentDate_Change();
        chkByNumberofPayments_Change();
      }

      RestructureOptions_Change(sender, e, "RestructureHoldToOriginalMaturityDate");
    }

    function chkHoldFinalPaymentDate_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;      

      // Uncheck Others
      if (C.chkHoldFinalPaymentDate.Value()) {
        C.chkHoldToOriginalMaturityDate.Value(false);
        C.chkByNumberofPayments.Value(false);
        chkHoldToOriginalMaturityDate_Change();
        chkByNumberofPayments_Change();
      }

      RestructureOptions_Change(sender, e, "RestructureHoldFinalPaymentDate");
    }

    function chkByNumberofPayments_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Uncheck Others
      if (C.chkByNumberofPayments.Value()) {
        C.chkHoldToOriginalMaturityDate.Value(false);
        C.chkHoldFinalPaymentDate.Value(false);
        chkHoldToOriginalMaturityDate_Change();
        chkHoldFinalPaymentDate_Change();
      }

      RestructureOptions_Change(sender, e, "RestructureNumberOfPayments");
    }

    function RestructureOptions_Change(sender, e, fieldUpdated) {
      // Update Controls
      C.datePaymentFinalDate.VisibleRow(C.chkHoldFinalPaymentDate.Value());
      C.numNumberofPayments.VisibleRow(C.chkByNumberofPayments.Value());
      C.numPaymentRegular.ReadOnly(C.chkHoldToOriginalMaturityDate.Value() || C.chkHoldFinalPaymentDate.Value() || C.chkByNumberofPayments.Value());

      // Run usual on change event
      if (sender) {
        if (C.chkHoldFinalPaymentDate.Value() && !C.datePaymentFinalDate.Value()) {
          // Do not refresh, data is not available yet
        }
        else if (C.chkByNumberofPayments.Value() && !C.numNumberofPayments.Value()) {
          // Do not refresh, data is not available yet
        }
        else {
          OnChange(sender, { fieldUpdated: fieldUpdated });
        }
      }
    }

    function cboInterestType_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Reset if blanked
      if (C.cboInterestType.ListIndex() == -1) C.cboInterestType.Text(mRecord.InterestTypeText);

      // Update Controls
      if (C.cboInterestType.ListIndex() == -1) {
        // Ignore
      }
      else {        
        switch (mConfig.InterestTypeList[C.cboInterestType.ListIndex()].Code) {
          case "FixedRate":
            C.numInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestRateTable.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(false);
            C.numInterestRateBase.VisibleRow(false);
            break;

          case "FloatingRate":
            C.numInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestRateTable.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(mConfig.OptionAllowInterest);
            C.numInterestRateBase.VisibleRow(mConfig.OptionAllowInterest);
            break;

          case "InterestFree":
            C.numInterestRate.VisibleRow(false);
            C.cboInterestRateTable.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(false);
            C.numInterestRateBase.VisibleRow(false);
            break;

          case "NotApplicable":
            C.numInterestRate.VisibleRow(false);
            C.cboInterestRateTable.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(false);
            C.numInterestRateBase.VisibleRow(false);
            break;

          case "RateTable":
            C.numInterestRate.VisibleRow(false);
            C.cboInterestRateTable.VisibleRow(mConfig.OptionAllowInterest);
            C.numInterestRatePremium.VisibleRow(mConfig.OptionAllowInterest);
            C.numInterestRateBase.VisibleRow(false);
            break;

          default:
            console.warn("widget_ui.AccountFinancial: Unhandled Interest Type '" + mConfig.InterestTypeList[C.cboInterestType.ListIndex()].Code + "'");
        }
      }

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "InterestType" });
    }

    function cboInterestPaymentType_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Reset if blanked
      if (C.cboInterestPaymentType.ListIndex() == -1) C.cboInterestPaymentType.Text(mRecord.InterestPaymentTypeText);

      // Notify
      if (sender) OnChange();
    }

    function cboMinimumPaymentBasis_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Used?
      if (!mConfig.OptionAllowMinimumPayment) return;

      // Update Controls
      switch (mConfig.MinimumPaymentBasisList[C.cboMinimumPaymentBasis.ListIndex()].Code) {
        case "None":
        case "InterestAndFeesOnly":
        case "InterestAndFeesBalance":
        case "InterestBalance":
        case "InterestOnly":    
          C.numMinimumPaymentValue.VisibleRow(false);
          C.numMinimumPaymentPercent.VisibleRow(false);
          C.dateMinimumPaymentInstalmentEndDate.VisibleRow(false);
          C.numMinimumPaymentInstalmentResidualValue.VisibleRow(false);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
          break;                  

        case "Instalment":
          C.numMinimumPaymentValue.VisibleRow(false);
          C.numMinimumPaymentPercent.VisibleRow(false);
          C.dateMinimumPaymentInstalmentEndDate.VisibleRow(true);
          C.numMinimumPaymentInstalmentResidualValue.VisibleRow(true);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
          break;

        case "OngoingSetValue":
        case "SetValue":
          C.numMinimumPaymentValue.VisibleRow(true);
          C.numMinimumPaymentPercent.VisibleRow(false);
          C.dateMinimumPaymentInstalmentEndDate.VisibleRow(false);
          C.numMinimumPaymentInstalmentResidualValue.VisibleRow(false);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
          break;

        case "PercentOfBalance":
          C.numMinimumPaymentValue.VisibleRow(false);
          C.numMinimumPaymentPercent.VisibleRow(true);
          C.dateMinimumPaymentInstalmentEndDate.VisibleRow(false);
          C.numMinimumPaymentInstalmentResidualValue.VisibleRow(false);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
          break;

        default:
          C.numMinimumPaymentValue.VisibleRow(true);
          C.numMinimumPaymentPercent.VisibleRow(true);
          C.dateMinimumPaymentInstalmentEndDate.VisibleRow(false);
          C.numMinimumPaymentInstalmentResidualValue.VisibleRow(false);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
      }

      // Notify
      if (sender) OnChange();
    }

    function dateOpeningDate_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Sync First Payment Date
      if (C.dateOpeningDate.Value() && C.datePaymentFirstDate.ReadOnly() || !C.datePaymentFirstDate.Value()) {
        C.datePaymentFirstDate.Value(C.dateOpeningDate.Value());
      }

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "OpeningDate" });
    }

    function chkMinimumPaymentDueDaysOverride_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update Controls
      C.numMinimumPaymentDueDays.ReadOnly(!C.chkMinimumPaymentDueDaysOverride.Value());

      // Notify
      if (sender) OnChange();
    }

    function cboMinimumPaymentHoldToPeriod_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update Controls
      if (C.cboMinimumPaymentHoldToPeriod.Text().toUpperCase() == "ON DATE") {
        C.dateMinimumPaymentHoldToDate.VisibleRow(true);
      }
      else {
        C.dateMinimumPaymentHoldToDate.VisibleRow(false);
      }

      // Notify
      if (sender) OnChange();
    }

    function cboTermCycle_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update Controls
      if (C.cboTermCycle.Text().toUpperCase() == "ON DATE") {
        C.dateTermCycleOnDate.VisibleRow(true);
      }
      else {
        C.dateTermCycleOnDate.VisibleRow(false);
      }

      // Notify
      if (sender) OnChange();
    }

    function dateMaturityDate_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update Controls
      if (C.dateMaturityDate.Value()) {
        C.dateMinimumPaymentInstalmentEndDate.AllowBlank(true);
        C.dateMinimumPaymentInstalmentEndDate.BlankTip(widget.FormatDate(C.dateMaturityDate.Value()));
      }
      else {
        C.dateMinimumPaymentInstalmentEndDate.AllowBlank(false);
        C.dateMinimumPaymentInstalmentEndDate.BlankTip("");
      }

      // Notify
      if (sender) OnChange();
    }

    function cboPaymentCycle_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "PaymentCycle" });
    }

    function cboPaymentFirstDatePeriod_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update Controls
      if (C.cboPaymentFirstDatePeriod.Text().toUpperCase() == "ON DATE" && !mOptions.isRestructure) {
        C.datePaymentFirstDate.VisibleRow(true);
      }
      else {
        C.datePaymentFirstDate.VisibleRow(false);
      }

      // Notify
      if (sender) OnChange();
    }

    function numPaymentRegular_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      if (C.numPaymentRegular.ValueIsBlank()) {
        C.numTermNumberOfPayments.ReadOnly(false);
        C.cboTermCycle.ReadOnly(false);
      }
      else {
        C.numTermNumberOfPayments.ReadOnly(true);
        C.cboTermCycle.ReadOnly(true);
      }

      // Notify
      if (sender) OnChange();
    }

    function cboStartupInterestPeriod_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Used?
      if (!mConfig.OptionAllowStartupInterest) return;

      // Update Controls
      if (C.cboStartupInterestPeriod.Text().toUpperCase() == "TO DATE") {
        if (C.cboStartupInterestType.ListIndex() != -1 && mConfig.StartupInterestTypeList[C.cboStartupInterestType.ListIndex()].Code != "NotApplicable") {
          C.dateStartupInterestToDate.VisibleRow(true);
        }
        else {
          C.dateStartupInterestToDate.VisibleRow(false);
        }
      }
      else {
        C.dateStartupInterestToDate.VisibleRow(false);
      }

      // Notify
      if (sender) OnChange();
    }

    function numStartupInterestRate_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "StartupInterestRate" });
    }

    function numInterestRate_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Notify
      if (sender) OnChange(sender, { fieldUpdated: "InterestRate" });
    }

    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement(refetchWarningMessage) {
      var showPayments = false;

      // Visibility
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }

      // Layout and Configuration
      // NOTE: Do not arbitrarily hide controls since they lose focus!
      if (mRecord) {
        // Layout
        if (mConfig.OptionShowFinancialPageOverridingPaymentsTab) {
          C.cmdOverridingPayments.show();
        }
        else {
          C.cmdOverridingPayments.hide();
        }

        // Account Class-specific
        switch (mRecord.AccountClass) {
          case "Deposit":
            // -------
            // Deposit
            // -------
            C.lblTerm.Text("Term");
            C.cboTermCycle.VisibleRow(!mConfig.TermOnCall);
            C.dateMaturityDate.VisibleRow(false);
            C.numTermNumberOfPayments.VisibleRow(false);
            C.lblMinimumPayments.VisibleRow(false);
            C.lblPayments.VisibleRow(false);
            C.cboPaymentCycle.VisibleRow(false);
            C.cboPaymentFirstDatePeriod.VisibleRow(false);
            C.datePaymentFirstDate.VisibleRow(false);
            C.numPaymentRegular.VisibleRow(false);
            C.numPaymentBalloon.VisibleRow(false);
            C.lblResidualValue.VisibleRow(false);
            C.numResidualValue.VisibleRow(false);          

            C.lblTaxCategory.VisibleRow(mConfig.OptionAllowTaxCategory);
            C.cboTaxCategory.VisibleRow(mConfig.OptionAllowTaxCategory);

            C.lblInterest.VisibleRow(true);
            C.cboInterestCycle.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.cboInterestCycle.ReadOnly(!mConfig.NewAccountWizard_InterestCycleUpdateable);
            C.dateInterestCycleDateFirst.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.dateInterestCycleDateFirst.ReadOnly(!mConfig.NewAccountWizard_InterestCycleUpdateable);
            C.cboInterestPaymentType.VisibleRow(true);

            C.lblInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestType.VisibleRow(mConfig.OptionAllowInterest);

            if (C.cmdSchedule) C.cmdSchedule.show();
            if (C.cmdResetFinancial) C.cmdResetFinancial.show();
            break;

          case "Disbursement":
            // ------------
            // Disbursement
            // -----------
            C.lblTerm.Text("Opening date");
            C.cboTermCycle.VisibleRow(false);
            C.dateMaturityDate.VisibleRow(false);
            C.numTermNumberOfPayments.VisibleRow(false);
            C.lblMinimumPayments.VisibleRow(false);
            C.lblPayments.VisibleRow(false);
            C.cboPaymentCycle.VisibleRow(false);
            C.cboPaymentFirstDatePeriod.VisibleRow(false);
            C.datePaymentFirstDate.VisibleRow(false);
            C.numPaymentRegular.VisibleRow(false);
            C.numPaymentBalloon.VisibleRow(false);
            C.lblResidualValue.VisibleRow(false);
            C.numResidualValue.VisibleRow(false);

            C.lblTaxCategory.VisibleRow(false);
            C.cboTaxCategory.VisibleRow(false);

            C.cboInterestCycle.VisibleRow(false);
            C.dateInterestCycleDateFirst.VisibleRow(false);

            C.lblInterest.VisibleRow(false);
            C.cboInterestPaymentType.VisibleRow(false);
            C.dateInterestCycleDateFirst.VisibleRow(false);

            C.lblStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestType.VisibleRow(false);
            C.cboStartupInterestPeriod.VisibleRow(false);
            C.numStartupInterestRate.VisibleRow(false);
            C.numStartupInterestRatePremium.VisibleRow(false);
            C.numStartupInterestRateBase.VisibleRow(false);
            C.dateStartupInterestToDate.VisibleRow(false);

            C.lblInterestRate.VisibleRow(false);
            C.cboInterestType.VisibleRow(false);
            C.cboInterestCycle.VisibleRow(false);
            C.numInterestRate.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(false);
            C.dateInterestCycleDateFirst.VisibleRow(false);

            C.lblOtherInterest.VisibleRow(false);
            C.numOtherInterestRate.VisibleRow(false);

            C.lblInterestInstructions.VisibleRow(false);
            C.cboInterestInstructionDown.VisibleRow(false);
            C.cboInterestInstructionUp.VisibleRow(false);
            C.chkPaymentsInAdvance.VisibleRow(false);
            C.chkOptionPaymentsFinalPlusBalloon.VisibleRow(false);
            C.cboOptionPaymentAllocationMethod.VisibleRow(false);

            if (C.cmdSchedule) C.cmdSchedule.hide();
            if (C.cmdResetFinancial) C.cmdResetFinancial.hide();
            break;

          case "LoanFT":
            // ----------
            // Fixed Term
            // ----------
            showPayments = true;

            C.lblTerm.Text("Term");
            switch (mConfig.TermEntryMethod) {
              case "NumberOfPayments":
                C.cboTermCycle.VisibleRow(false);
                C.numTermNumberOfPayments.VisibleRow(true);
                break;

              case "Term":
                C.cboTermCycle.VisibleRow(true);
                C.numTermNumberOfPayments.VisibleRow(false);
                break;
            }

            C.dateTermCycleOnDate.VisibleRow(false);
            C.dateMaturityDate.VisibleRow(false);

            C.lblMinimumPayments.VisibleRow(false);

            C.lblPayments.VisibleRow(true);
            C.cboPaymentCycle.VisibleRow(true);            

            C.lblTaxCategory.VisibleRow(false);
            C.cboTaxCategory.VisibleRow(false);

            C.lblInterest.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.cboInterestCycle.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.cboInterestCycle.ReadOnly(!mConfig.NewAccountWizard_InterestCycleUpdateable);
            C.dateInterestCycleDateFirst.VisibleRow(false);
            C.cboInterestPaymentType.VisibleRow(false);

            C.lblInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestType.VisibleRow(mConfig.OptionAllowInterest);

            C.lblInterestInstructions.VisibleRow(false);
            C.cboInterestInstructionDown.VisibleRow(false);
            C.cboInterestInstructionUp.VisibleRow(false);
            C.chkPaymentsInAdvance.VisibleRow(true);
            C.chkOptionPaymentsFinalPlusBalloon.VisibleRow(mConfig.OptionAllowBalloonPayment);
            C.cboOptionPaymentAllocationMethod.VisibleRow(mConfig.OptionAllowBalloonPayment);

            if (C.cmdSchedule) C.cmdSchedule.show();
            if (C.cmdResetFinancial) C.cmdResetFinancial.show();
            break;

          case "LoanFR":
            // -------------
            // Floating Rate
            // -------------
            showPayments = true;

            C.lblTerm.Text("Term");
            switch (mConfig.TermEntryMethod) {
              case "NumberOfPayments":
                C.cboTermCycle.VisibleRow(false);
                C.numTermNumberOfPayments.VisibleRow(true);
                break;

              case "Term":
                C.cboTermCycle.VisibleRow(true);
                C.numTermNumberOfPayments.VisibleRow(false);
                break;
            }

            C.dateTermCycleOnDate.VisibleRow(false);
            C.dateMaturityDate.VisibleRow(false);

            C.lblMinimumPayments.VisibleRow(false);

            C.lblPayments.VisibleRow(true);
            C.cboPaymentCycle.VisibleRow(true);

            C.lblTaxCategory.VisibleRow(false);
            C.cboTaxCategory.VisibleRow(false);

            C.lblInterest.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.cboInterestCycle.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.cboInterestCycle.ReadOnly(!mConfig.NewAccountWizard_InterestCycleUpdateable);
            C.dateInterestCycleDateFirst.VisibleRow(false);
            C.cboInterestPaymentType.VisibleRow(false);

            C.lblInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestType.VisibleRow(mConfig.OptionAllowInterest);

            C.lblInterestInstructions.VisibleRow(true);
            C.cboInterestInstructionDown.VisibleRow(true);
            C.cboInterestInstructionUp.VisibleRow(true);
            C.chkPaymentsInAdvance.VisibleRow(true);
            C.chkOptionPaymentsFinalPlusBalloon.VisibleRow(mConfig.OptionAllowBalloonPayment);
            C.cboOptionPaymentAllocationMethod.VisibleRow(mConfig.OptionAllowBalloonPayment);

            if (C.cmdSchedule) C.cmdSchedule.show();
            if (C.cmdResetFinancial) C.cmdResetFinancial.show();
            break;

          case "LoanRC":
            // ----------------
            // Revolving Credit
            // ----------------
            C.lblTerm.Text("Opening date");
            C.cboTermCycle.VisibleRow(false);
            C.numTermNumberOfPayments.VisibleRow(false);
            C.dateTermCycleOnDate.VisibleRow(false);
            C.dateMaturityDate.VisibleRow(true);

            C.lblMinimumPayments.VisibleRow(true);

            C.lblPayments.VisibleRow(false);
            C.cboPaymentCycle.VisibleRow(false);
            C.cboPaymentFirstDatePeriod.VisibleRow(false);
            C.datePaymentFirstDate.VisibleRow(false);
            C.numPaymentRegular.VisibleRow(false);
            C.numPaymentBalloon.VisibleRow(false);

            C.lblResidualValue.VisibleRow(false);
            C.numResidualValue.VisibleRow(false);

            C.lblTaxCategory.VisibleRow(false);
            C.cboTaxCategory.VisibleRow(false);

            C.lblInterest.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.cboInterestCycle.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.cboInterestCycle.ReadOnly(!mConfig.NewAccountWizard_InterestCycleUpdateable);
            C.dateInterestCycleDateFirst.VisibleRow(mConfig.OptionAllowInterestCycle);
            C.dateInterestCycleDateFirst.ReadOnly(!mConfig.NewAccountWizard_InterestCycleUpdateable);
            C.cboInterestPaymentType.VisibleRow(false);

            C.lblInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestType.VisibleRow(mConfig.OptionAllowInterest);

            C.lblInterestInstructions.VisibleRow(false);
            C.cboInterestInstructionDown.VisibleRow(false);
            C.cboInterestInstructionUp.VisibleRow(false);
            C.chkPaymentsInAdvance.VisibleRow(false);
            C.chkOptionPaymentsFinalPlusBalloon.VisibleRow(false);
            C.cboOptionPaymentAllocationMethod.VisibleRow(false);

            if (C.cmdSchedule) C.cmdSchedule.show();
            if (C.cmdResetFinancial) C.cmdResetFinancial.show();
            break;

          default:
            console.warn("widget_ui.AccountFinancial: AccountClass '" + mRecord.AccountClass + "' not handled.");
        }
      }
      
      // Show Payment Schedule?
      if (mOptions.allowPaymentSchedule) {
        if (!mRecord) {
          showPayments = false;
        }
        else if (mRecord && !mRecord.PaymentSchedule) {
          showPayments = false;
        }
        else if (mRecord && !mRecord.PaymentSchedule.Items) {
          showPayments = false;
        }
        
        // Show or Hide Payment Schedule button
        if (showPayments) {
          C.cmdPaymentSchedule.show();
        }
        else {
          C.cmdPaymentSchedule.hide();
        }
      }      
        
      // Restructure handling
      if (mOptions.isRestructure) {
        // Term selection not available for Restructures
        C.lblTerm.VisibleRow(false);
        C.dateOpeningDate.VisibleRow(false);
        C.cboTermCycle.VisibleRow(false);
        C.dateTermCycleOnDate.VisibleRow(false);
        C.dateMaturityDate.VisibleRow(false);
        C.numTermNumberOfPayments.VisibleRow(false);
      }

      // Refinance Handling
      if (mOptions.isRefinance) {
        C.dateOpeningDate.ReadOnly(true);
      }
      else {
        C.dateOpeningDate.ReadOnly(false);
      }
    }

    // -------------
    // Add a Promise
    // -------------
    function showPromiseAdd() {
      // Create Modal
      mForm_PromiseAdd = widget.UI.Modal({
        title: "Add Promise",
        width: "90%",
        height: "95%",
        maxWidth: 400,
        maxHeight: 400,
        minWidth: 400,
        minHeight: 400,

        onAction: showPromiseAdd_Action,
      });

      // Actions
      mForm_PromiseAdd.Actions().Define([{ groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
                                         { groupId: "[buttons]", actionId: "Ok", caption: "Apply Changes" }]);

      // Define HTML Content
      var content = "";
      content += "<div class='is-widget-form-body' style='position: absolute; top: 0; left: 0; right: 0; bottom: 0;'>";

      // Show (content will be set in the next block)
      mForm_PromiseAdd.Show({ content: content });      

      // Render
      var e = $("div", mForm_PromiseAdd.ContentElement());

      var tr;
      var cid = CreateGuid(true);
      var table = $("<table class='is-form'></table>");
      table.append("<colgroup><col style='width:8em;'/><col/><col><col/></colgroup>");
      e.append(table);

      cid += "X";
      tr = $("<tr><th colspan='2'><label id='" + cid + "'>New Promise details</label></th></tr>");
      table.append(tr);
      C_PromiseAdd.lblPromiseAdd = Label($("label", tr), {});
      
      cid += "X";
      tr = $("<tr><th colspan=2'><input id='" + cid + "' type='checkbox' /></th></tr>");
      table.append(tr);
      C_PromiseAdd.chkPromisesClear = CheckBox($("input", tr), {
        caption: "Clear existing promises?",

        onChange: divPromiseInformation_Refresh,
      });

      cid += "X";
      tr = $("<tr><th><label for='" + cid + "'>Total:</label></th><td><input id='" + cid + "'/></td></tr>");
      table.append(tr);
      C_PromiseAdd.numPromiseTotal = NumberBox($("input", tr), {
        allowBlank: false,
        minValue: 0,
        maxValue: 999999999999,

        onChange: numPromiseTotal_Change,
      });

      cid += "X";
      tr = $("<tr><th><label for='" + cid + "'>Frequency:</label></th><td><input id='" + cid + "'/></td></tr>");
      table.append(tr);
      C_PromiseAdd.cboPromiseFrequency = DateCycleComboBox($("input", tr), {
        allowBlank: false,
        isFrequency: true,

        onChange: divPromiseInformation_Refresh,
      });      

      cid += "X";
      tr = $("<tr><th><label for='" + cid + "'>First Date:</label></th><td><input id='" + cid + "'/></td></tr>");
      table.append(tr);
      C_PromiseAdd.datePromiseFirst = DateBox($("input", tr), {
        allowBlank: false,
        showWeekDayName: true,

        onChange: divPromiseInformation_Refresh,
      });

      cid += "X";
      tr = $("<tr><th><label for='" + cid + "'>Value:</label></th><td><input id='" + cid + "'/></td></tr>");
      table.append(tr);
      C_PromiseAdd.numPromiseValue = NumberBox($("input", tr), {
        allowBlank: false,
        minValue: 0,
        maxValue: 999999999999,

        onChange: numPromiseValue_Change,
      });

      cid += "X";
      tr = $("<tr><th><label for='" + cid + "'>No. Payments:</label></th><td><input id='" + cid + "'/></td></tr>");
      table.append(tr);
      C_PromiseAdd.numPromiseNumberOfPayments = NumberBox($("input", tr), {
        allowBlank: true,
        decimals: 0,
        minValue: 0,
        maxValue: 9999,

        onChange: numPromiseNumberOfPayments_Change,
      });

      cid += "X";
      tr = $("<tr><th colspan='2'><div id='" + cid + "' class='is-info-text info small'></div></th></tr>");
      table.append(tr);
      C_PromiseAdd.divPromiseInformation = $("#" + cid, tr);

      // Initialise Controls
      C_PromiseAdd.chkPromisesClear.Value(true);
      C_PromiseAdd.numPromiseTotal.Value(mRecord.RestructureBalanceOverdue);
      C_PromiseAdd.cboPromiseFrequency.ListFromCsvString(mConfig.PaymentCycleList);
      C_PromiseAdd.datePromiseFirst.Value(C.datePaymentNextDate.Value());
      C_PromiseAdd.cboPromiseFrequency.Text(C.cboPaymentCycle.Text());
      C_PromiseAdd.numPromiseValue.Value(0);

      divPromiseInformation_Refresh();
    }

    // Handle Actions
    function showPromiseAdd_Action(actionId) {
      switch (actionId) {
        case "Cancel":
          mForm_PromiseAdd.Close();
          break;

        case "Ok":
          showPromiseAdd_Action_Ok();
          break;

        default:
          window.alert(actionId);
      }
    }

    function showPromiseAdd_Action_Ok() {
      // Validate
      var Ok = widget.UI.ValidateContainer(mForm_PromiseAdd.ContentElement());

      if (Ok) {
        var o = {
          PromiseTotal: C_PromiseAdd.numPromiseTotal.Value(),
          PromiseFrequency: C_PromiseAdd.cboPromiseFrequency.Text(),
          PromiseFirstDate: C_PromiseAdd.datePromiseFirst.Value(),
          PromiseValue: C_PromiseAdd.numPromiseValue.Value(),
          PromiseCount: C_PromiseAdd.numPromiseNumberOfPayments.Value(),
          ClearExistingPromises: C_PromiseAdd.chkPromisesClear.Value(),
        };
        mPromises.push(o);

        // Recalculate and Refresh
        OnChange();

        // Close
        mForm_PromiseAdd.Close();
      }      
    }

    function divPromiseInformation_Refresh(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Update information
      var s = "";
      var PromiseCount = 0;
      if (mPayments) {
        for (var i = 0; i < mPayments.length; i++) {
          if (mPayments[i].PaymentType == "Promise") PromiseCount++;
        }
      }

      if (C_PromiseAdd.chkPromisesClear.Value()) {
        switch (PromiseCount) {
          case 0:
            //s += "<span style='color:red'>There are no existing promises to clear.</span><br/><br/>";
            break;

          case 1:
            s += "Clear <b>" + PromiseCount + "</b> existing promise.<br/><br/>";
            break;

          default:
            s += "Clear <b>" + PromiseCount + "</b> existing promises.<br/><br/>";
            break;
        }
      }

      if (C_PromiseAdd.numPromiseValue.Value() <= 0) {
        s += "<span style='color:red'>Enter a Promise Value</span>.";
      }
      else if (C_PromiseAdd.numPromiseNumberOfPayments.Value() == 0) {
        s += "Make payments of <b>" + widget.FormatCurrency(C_PromiseAdd.numPromiseValue.Value(), true) + "</b> up to a maximum of <b>" + widget.FormatCurrency(C_PromiseAdd.numPromiseTotal.Value(), true) + "</b>.";
      }
      else if (C_PromiseAdd.numPromiseNumberOfPayments.Value() == 1) {
        s += "Make a single payment of <b>" + widget.FormatCurrency(C_PromiseAdd.numPromiseValue.Value(), true) + "</b>";
      }
      else {
        if (C_PromiseAdd.numPromiseNumberOfPayments.Value() * C_PromiseAdd.numPromiseValue.Value() == C_PromiseAdd.numPromiseTotal.Value()) {
          s += "Make <b>" + C_PromiseAdd.numPromiseNumberOfPayments.Value() + "</b> payments of <b>" + widget.FormatCurrency(C_PromiseAdd.numPromiseValue.Value(), true) + "</b>";
        }
        else {
          s += "Make " + (C_PromiseAdd.numPromiseNumberOfPayments.Value() - 1) + " payments of <b>" + widget.FormatCurrency(C_PromiseAdd.numPromiseValue.Value(), true) + "</b>";
          s += " and 1 of <b>" + widget.FormatCurrency(C_PromiseAdd.numPromiseTotal.Value() - (C_PromiseAdd.numPromiseNumberOfPayments.Value() - 1) * C_PromiseAdd.numPromiseValue.Value(), true) + "</b>.";
        }
      }
      s += "<br/><br/>";
      if (C_PromiseAdd.cboPromiseFrequency.Text()) s += "Pay <b>" + widget.UI.HtmlEncode(C_PromiseAdd.cboPromiseFrequency.Text()) + "</b>";
      if (C_PromiseAdd.datePromiseFirst.Value()) s += " starting on <b> " + widget.GetWeekDayNameFromDate(C_PromiseAdd.datePromiseFirst.Value()) + " " + widget.FormatDate(C_PromiseAdd.datePromiseFirst.Value()) + "</b>";
      s += ".<br/>";

      C_PromiseAdd.divPromiseInformation.html(s);
    }

    function numPromiseTotal_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      if (C_PromiseAdd.numPromiseValue.Value() > 0) {
        // Calculate number of payments
        C_PromiseAdd.numPromiseNumberOfPayments.Value(Math.ceil(C_PromiseAdd.numPromiseTotal.Value() / C_PromiseAdd.numPromiseValue.Value()));
      }
      else if (C_PromiseAdd.numPromiseNumberOfPayments.Value() > 0 && C_PromiseAdd.numPromiseTotal.Value() > 0) {
        // Calculate promise value
        C_PromiseAdd.numPromiseValue.Value(widget.RoundCurrencyUp(C_PromiseAdd.numPromiseTotal.Value() / C_PromiseAdd.numPromiseNumberOfPayments.Value()));
      }

      // Refresh information
      divPromiseInformation_Refresh();
    }

    function numPromiseValue_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Calculate number of payments
      if (C_PromiseAdd.numPromiseValue.Value() > 0) {
        if (C_PromiseAdd.numPromiseTotal.Value() <= 0) {
          if (C_PromiseAdd.numPromiseNumberOfPayments.Value() <= 1) C_PromiseAdd.numPromiseNumberOfPayments.Value(1);
          C_PromiseAdd.numPromiseTotal.Value(widget.RoundCurrencyUp(C_PromiseAdd.numPromiseValue.Value() * C_PromiseAdd.numPromiseNumberOfPayments.Value()));
        }
        else {
          C_PromiseAdd.numPromiseNumberOfPayments.Value(Math.ceil(C_PromiseAdd.numPromiseTotal.Value() / C_PromiseAdd.numPromiseValue.Value()));
        }
      }

      // Refresh information
      divPromiseInformation_Refresh();
    }

    function numPromiseNumberOfPayments_Change(sender, e) {
      // Handled
      if (e) e.ChangeHandled = true;

      // Calculate promise value
      if (C_PromiseAdd.numPromiseNumberOfPayments.Value() > 0) {
        if (C_PromiseAdd.numPromiseValue.Value() > 0 && C_PromiseAdd.numPromiseTotal.Value() == 0) {
          C_PromiseAdd.numPromiseTotal.Value(widget.RoundCurrencyUp(C_PromiseAdd.numPromiseValue.Value() * C_PromiseAdd.numPromiseNumberOfPayments.Value()));
        }
        else if (C_PromiseAdd.numPromiseTotal.Value() > 0) {
          C_PromiseAdd.numPromiseValue.Value(widget.RoundCurrencyUp(C_PromiseAdd.numPromiseTotal.Value() / C_PromiseAdd.numPromiseNumberOfPayments.Value()));
        }
      }

      // Refresh information
      divPromiseInformation_Refresh();
    }

    // ===============
    // numInterestRate
    // ===============
    function numInterestRate_ButtonClick(sender, e) {
      switch (e.id) {
        case "TotalInterest":
          SetTotalInterest();
          break;

      }
    }

    // ==============================================================================================================================================================================================================================
    // Sets the Account Id. Used if the Account Id is known, for instance editing a Quote Account. Required for passing to the Standard Transaction HTML Widget for PayTo integration so Agreements can be retrieved for the Account.
    // ==============================================================================================================================================================================================================================
    function SetAccountId(accountId) {
      if (!mRecord) return;

      // Update
      mRecord.AccountId = accountId;
      
      // Update Controls
      UpdateElement();
    }

    // ==================
    // Set Total Interest
    // ==================
    function SetTotalInterest() {
      // Create Modal
      mForm_TotalInterest = widget.UI.Modal({
        title: "Calculate Interest Rate from Total Interest",
        width: "540px",
        height: "180px",
        maxWidth: 500,
        maxHeight: 500,

        onAction: totalInterest_Action,
      });

      // Actions
      mForm_TotalInterest.Actions().Define([{ groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
                                            { groupId: "[buttons]", actionId: "Ok", caption: "Ok" }]);

      // Define HTML Content
      var content = "";
      content += "<div class='is-widget-form-body' style='position: absolute; top: 0; left: 0; right: 0; bottom: 0;'>";

      // Show (content will be set in the next block)
      mForm_TotalInterest.Show({ content: content });

      // Render
      var e = $("div", mForm_TotalInterest.ContentElement());

      // Controls
      var tr;
      var cid = CreateGuid(true);
      var table = $("<table class='is-form'></table>");
      table.append("<colgroup><col style='width:8em;'/><col/><col><col/></colgroup>");
      e.append(table);

      cid += "X";
      tr = $("<tr><th colspan='2'><label id='" + cid + "'>Enter Total Interest value</label></th></tr>");
      table.append(tr);
      C_TotalInterest.lblTotalInterest = Label($("label", tr), {});

      cid += "X";
      tr = $("<tr><th><label for='" + cid + "'>Interest Value:</label></th><td><input id='" + cid + "'/></td></tr>");
      table.append(tr);
      C_TotalInterest.numTotalInterest = NumberBox($("input", tr), {
        allowBlank: false,
        minValue: 0,
        maxValue: 999999999999,
      });

      // Default Total Interest
      C_TotalInterest.numTotalInterest.Value(mRecord.TotalInterest);
    }

    // Handle Actions
    function totalInterest_Action(actionId) {
      switch (actionId) {
        case "Cancel":
          mForm_TotalInterest.Close();
          break;

        case "Ok":
          totalInterest_Action_Ok();
          break;

        default:
          window.alert(actionId);
      }
    }

    function totalInterest_Action_Ok() {      
      // Validate
      var Ok = widget.UI.ValidateContainer(mForm_TotalInterest.ContentElement());

      if (Ok) {
        // Total Interest
        mRecord.TotalInterestOverride = C_TotalInterest.numTotalInterest.Value();

        // Recalculate and Refresh
        OnChange();

        // Close
        mForm_TotalInterest.Close();
      }      
    }

    // -------------------------------
    // View / Edit Overriding Payments
    // -------------------------------
    function showOverridingPayments() {
      // Create Modal
      mForm_OverridingPayments = widget.UI.Modal({
        title: "Overriding Payments",
        width: "90%",
        height: "95%",
        maxWidth: 1000,
        maxHeight: 1400,
        minWidth: 600,
        minHeight: 400,

        onAction: showOverridingPayments_Action,
      });

      // Actions
      mForm_OverridingPayments.Actions().Define([{ groupId: "[buttons]", actionId: "Cancel", caption: "Cancel" },
                                                 { groupId: "[buttons]", actionId: "Ok", caption: "Apply Changes" }]);

      // Define HTML Content
      var content = "";      
      content += "<div class='is-widget-form-body' style='position: absolute; top: 0; left: 0; right: 0; bottom: 0;'>";

      // Show (content will be set in the next block)
      mForm_OverridingPayments.Show({ content: content });

      // Render
      var e = $("div", mForm_OverridingPayments.ContentElement());

      // Controls
      e.append("<div class='overriding-payments-grid'></div>");
      C_OverridingPayments.gridPayments = widget.UI.Grid($(".overriding-payments-grid", e), {
        stickyHeader: true,
        rowNumbering: true,
        allowAddRows: true,
        allowMultiRowSelect: true,
        showRowSelectors: true,
        maxNewRows: 100,

        onBeforeCellUpdate: gridPayments_BeforeCellUpdate,
        onInitialiseRow: gridPayments_InitialiseRow,
        onRowAdd: gridPayments_RowAdd,
        onAfterRowActivate: gridPayments_AfterRowActivate,
        onAction: gridPayments_Action,
      });

      // Clone Overriding Payments for Edit
      mPayments_Edit = JSON.parse(JSON.stringify(mPayments));

      // Refresh Grid
      // Tooltips
      var s = "Dates for 'Regular' Payment overrides may be entered as either a fixed date or a date range in the format ";
      switch (widget.DayMonthYearOrder()) {
        case "DMY":
          s += "[day/]month[/year][-[day/]month[/year]], where [] indicates optional items.\n\n";
          s += "Use numbers or * in day/month/year. If only one item Month is assumed.\n\n";
          s += "Examples:\n\n";
          s += "12 = December\n";
          s += "11-12 = November to December\n";
          s += "10/12-31/1 = 10th December to 31st January\n";
          s += "15/* = Every 15th day of the Month\n";
          s += "10/12/2018-30/6/2019 = 10/12/2018 to 30/6/2019\n";
          break;

        case "MDY":
          s += "month[[/day][/year]][-month[[/day][/year]]], where [] indicates optional items.\n\n";
          s += "Use numbers or * in day/month/year. If only one item Month is assumed.\n\n";
          s += "Examples:\n\n";
          s += "12 = December\n";
          s += "11-12 = November to December\n";
          s += "12/10-1/31 = 10th December to 31st January\n";
          s += "*/15 = Every 15th day of the Month\n";
          s += "12/10/2018-6/30/2019 = 12/10/2018 to 6/30/2019\n";
          break;

        case "YMD":
          s += "[year/]month[/day][-[year/]month[/day]], where [] indicates optional items.\n\n";
          s += "Use numbers or * in day/month/year. If only one item Month is assumed.\n\n";
          s += "Examples:\n\n";
          s += "12 = December\n";
          s += "11-12 = November to December\n";
          s += "12/10-1/31 = 10th December to 31st January\n";
          s += "*/15 = Every 15th day of the Month\n";
          s += "2018/12/10-2019/6/30 = 2018/12/10 to 2019/6/30\n";
          break;
      }
      dateRangeTooltip = s;
      valueTooltip = "Regular Payment values may be entered as either a fixed value, blank (use regular payment), +value, -value, *value, /value or value%";
      
      // Add Columns
      C_OverridingPayments.gridPayments.ClearColumns();
      C_OverridingPayments.gridPayments.AddColumnIcon("PaymentTypeIcon", {});
      C_OverridingPayments.gridPayments.AddColumnString("PaymentTypeText", { caption: "Type", width: "6em", allowEdit: true, listCsv: mConfig.AccountCalcPaymentTypeList.ToDescriptionCsvList(), limitToList: true });

      if (mRecord.PaymentMethodIsDirectDebit && mOptions.isRestructure) {
        C_OverridingPayments.gridPayments.AddColumnBoolean("ManualPayment", { caption: "Manual", allowEdit: true, tooltipText: "If this payment is expected to be paid manually rather than by Direct Debit check the column" });
      }
      
      C_OverridingPayments.gridPayments.AddColumnDate("Date", { caption: "Date", allowEdit: true });
      C_OverridingPayments.gridPayments.AddColumnString("DateRange", { caption: "Date Range", width: "10em", allowEdit: !mRecord.Promise, tooltipText: dateRangeTooltip });
      C_OverridingPayments.gridPayments.AddColumnString("DateRangeDescription", { caption: "Description", width: "10em" });      
      C_OverridingPayments.gridPayments.AddColumnString("ValueText", { caption: "Value", align: "right", allowEdit: true, width: "6em", tooltipText: valueTooltip });
      C_OverridingPayments.gridPayments.AddColumnString("Notes", { caption: "Notes", allowEdit: true, maxLength: 50 });
      
      // Actions
      C_OverridingPayments.gridPayments.Actions().Define([
        { actionId: "ItemInsert", tooltipText: "Insert a row before the current row", icon: "Grid_Row_Insert" },
        { actionId: "SelectDelete", tooltipText: "Delete selected row(s)", icon: "Grid_Row_Delete" },
        {},
        { actionId: "RowMoveUp", tooltipText: "Move current row up", icon: "Grid_Row_MoveUp" },
        { actionId: "RowMoveDown", tooltipText: "Move current row down", icon: "Grid_Row_MoveDown" },
        {},
        { actionId: "SelectAll", tooltipText: "Select all rows", icon: "Select_All" },
        { actionId: "SelectNone", tooltipText: "Select no rows", icon: "Select_None" },
        { actionId: "SelectUp", tooltipText: "Select all rows above and including the current row", icon: "Select_Up" },
        { actionId: "SelectDown", tooltipText: "Select all rows below and including the current row", icon: "Select_Down" },
        { actionId: "SelectAllType", tooltipText: "Select all rows with the same Type as the current row", icon: "Select_Same" },
        {},
        { actionId: "RegularPaymentsCreate", tooltipText: "Create 'Blank' Regular Payments", icon: "Add" },
        { actionId: "RegularPaymentsClear", tooltipText: "Delete all Regular Payments", icon: "Delete" },
        {},
        { actionId: "PaymentsCleanup", tooltipText: "Clean-up and delete non-used and blank Payments", icon: "Sweep" }
      ]);

      // Refresh
      C_OverridingPayments.gridPayments.VirtualDataRefresh(mPayments_Edit);
    }

    function gridPayments_InitialiseRow(e) {
      var item = mPayments_Edit[e.row.listIndex];

      // Update cells
      e.row.cells.PaymentTypeText.value = item.PaymentTypeText;
      if (mRecord.PaymentMethodIsDirectDebit && mOptions.isRestructure) {
        e.row.cells.ManualPayment.value = item.ManualPayment;
      }      
      e.row.cells.Date.value = item.Date;
      e.row.cells.DateRange.value = item.DateRange;
      e.row.cells.DateRangeDescription.value = item.DateRangeDescription;
      e.row.cells.ValueText.value = item.ValueText;
      e.row.cells.Notes.value = item.Notes;

      // Icon
      switch (item.PaymentType) {
        case "Additional":
          e.row.cells.PaymentTypeIcon.value = "Payment_Additional";
          break;

        case "Promise":
          e.row.cells.PaymentTypeIcon.value = "Payment_Promise";
          break;

        case "Regular":
          e.row.cells.PaymentTypeIcon.value = "Payment_Overridden";
          break;

        default:
          e.row.cells.PaymentTypeIcon.value = "";
          break;
      }

      // Payment-Type specific
      switch (item.PaymentType) {
        case "Regular":
          if (item.DateRange && !item.DateRangeDescription) {
            // Fetched asynchronously for user data-entry
            e.row.cells.DateRangeDescription.value = { eventId: "GetDateRangeDescription", systemEvent: true, params: { dateRange: item.DateRange } };
          }
          else {
            e.row.cells.DateRangeDescription.value = item.DateRangeDescription;
          }
          e.row.cells.DateRangeDescription.small = true;
          break;

        default:
          e.row.cells.DateRangeDescription.value = "";
          break;
      }

      // Read-Only?
      e.row.cells.DateRangeDescription.readOnly = true; // This column is never editable so colour accordingly      
      if (item.PaymentType == "Regular") {
        e.row.cells.DateRange.readOnly = false;
      }
      else {
        e.row.cells.DateRange.readOnly = true;
      }

      // Validate Row
      e.row.invalid = false;
      if (!item.PaymentType) {
        e.row.invalid = true;
        e.row.invalidMessage = "Payment Type not specified.";
      }
      else if (!item.ValueText) {
        e.row.invalid = true;
        e.row.invalidMessage = "Value not specified.";
      }
      if (!e.row.invalid) {
        switch (item.PaymentType) {
          case "Regular":
            if (!item.Date && !item.DateRange) {
              e.row.invalid = true;
              e.row.invalidMessage = "Date or Date Range not specified.";
            }
            break;

          default:
            if (!item.Date) {
              e.row.invalid = true;
              e.row.invalidMessage = "Date not specified.";
            }
            break;
        }
      }

    }

    function gridPayments_RowAdd(e) {
      // Create item
      var item;
      if (mRecord.Promise) {
        item = {
          PaymentType: "Promise",
          PaymentTypeText: mConfig.AccountCalcPaymentTypeList.CodeToDescription("Promise"),
        };

        // Inherit some properties from previous row
        if (mPayments_Edit.length != 0) {
          var lastItem = mPayments_Edit[mPayments_Edit.length - 1];
          item.ValueText = lastItem.ValueText;
        }
      }
      else {
        item = {
          PaymentType: "Additional",
          PaymentTypeText: mConfig.AccountCalcPaymentTypeList.CodeToDescription("Additional"),
        };

        // Inherit some properties from previous row
        if (mPayments_Edit.length != 0) {
          var lastItem = mPayments_Edit[mPayments_Edit.length - 1];
          item.PaymentType = lastItem.PaymentType;
          item.PaymentTypeText = lastItem.PaymentTypeText;
          item.ValueText = lastItem.ValueText;
        }
      }

      // Add
      mPayments_Edit.push(item);
    }

    function gridPayments_BeforeCellUpdate(e) {
      var item = mPayments_Edit[e.row.listIndex];

      switch (e.columnKey) {
        case "Date":
          item.Date = e.newValue;

          if (item.Date) {
            // Clear Date Range
            item.DateRange = "";
          }
          break;

        case "DateRange":
          item.DateRange = e.newValue;

          if (item.DateRange) {
            // Clear Date
            item.Date = null;
            item.DateRangeDescription = null; // Force refetch
          }
          break;

        case "ManualPayment":
          item.ManualPayment = e.newValue;
          break;

        case "Notes":
          item.Notes = e.newValue;
          break;

        case "PaymentTypeText":
          item.PaymentTypeText = e.newValue;
          item.PaymentType = mConfig.AccountCalcPaymentTypeList.DescriptionToCode(e.newValue);
          break;

        case "ValueText":
          switch (item.PaymentType) {
            case "Promise":
              // Promise must be a literal value
              if (e.newValue == "") {
                item.ValueText = "";
              }
              else {
                item.ValueText = widget.FormatCurrency(widget.ParseCurrency(e.newValue));
              }
              break;

            default:
              item.ValueText = e.newValue;
              break;
          }
          break;
      }

      // Refresh row to update styles
      e.refreshRow = true;
    }

    function gridPayments_AfterRowActivate(e) {
      // Refresh Buttons
      gridPayments_RefreshButtons();
    }

    function gridPayments_RefreshButtons() {
      if (C_OverridingPayments.gridPayments.ActiveDataRowListIndex() == -1) {
        C_OverridingPayments.gridPayments.Actions().SetEnabled("DeleteRow", false);
      }
      else {
        var item = mPayments_Edit[C_OverridingPayments.gridPayments.ActiveDataRowListIndex()];
        C_OverridingPayments.gridPayments.Actions().SetEnabled("DeleteRow", !item.ReadOnly);
      }

      C_OverridingPayments.gridPayments.RefreshButtons();
    }

    function gridPayments_Action(actionId) {
      switch (actionId.toUpperCase()) {
        case "ITEMINSERT":
          var o = {
            Date: null,
            DateRange: "",
            DateRangeDescription: "",
            Ignored: false,
            ManualPayment: false,
            Notes: "",
            PaymentType: "Additional",
            PaymentTypeText: "Additional",
            ValueText: "",
            ValueType: "None",
          };
          mPayments_Edit.splice(C_OverridingPayments.gridPayments.ActiveDataRowListIndex(), 0, o);
          C_OverridingPayments.gridPayments.VirtualDataRefresh(mPayments_Edit, true);
          break;

        case "SELECTDELETE":
          C_OverridingPayments.gridPayments.RemoveSelectedRowsAndCollectionItems();
          break;

        case "ROWMOVEUP":
          C_OverridingPayments.gridPayments.RowMoveUp();
          break;

        case "ROWMOVEDOWN":
          C_OverridingPayments.gridPayments.RowMoveDown();
          break;

        case "SELECTALL":
          var indexes = [];
          for (var i = 0; i < mPayments_Edit.length; i++) {
            indexes.push(i);
          }
          C_OverridingPayments.gridPayments.SetSelectedRowIndexes(indexes, true);
          break;

        case "SELECTNONE":
          C_OverridingPayments.gridPayments.SetSelectedRowIndexes([], true);
          break;

        case "SELECTUP":
          var indexes = [];
          for (var i = 0; i < mPayments_Edit.length; i++) {
            if (i <= C_OverridingPayments.gridPayments.ActiveDataRowListIndex()) indexes.push(i);
          }
          C_OverridingPayments.gridPayments.SetSelectedRowIndexes(indexes, true);
          break;

        case "SELECTDOWN":
          var indexes = [];
          for (var i = 0; i < mPayments_Edit.length; i++) {
            if (i >= C_OverridingPayments.gridPayments.ActiveDataRowListIndex()) indexes.push(i);
          }
          C_OverridingPayments.gridPayments.SetSelectedRowIndexes(indexes, true);
          break;

        case "SELECTALLTYPE":
          var activeRowIndex = C_OverridingPayments.gridPayments.ActiveDataRowListIndex();
          if (activeRowIndex >= 0) var paymentType = mPayments_Edit[activeRowIndex].PaymentType;

          // Select matching Payment Types
          if (paymentType) {
            var selectedRows = [];
            for (var i = 0; i < mPayments_Edit.length; i++) {
              var item = mPayments_Edit[i];
              if (item.PaymentType == paymentType) selectedRows.push(i);
            }
            C_OverridingPayments.gridPayments.SetSelectedRowIndexes(selectedRows, true);
          }
          break;

        case "REGULARPAYMENTSCREATE":
          mOptions.onAction("RegularPaymentsCreate");
          break;

        case "REGULARPAYMENTSCLEAR":          
          var refresh = false;

          for (var i = mPayments_Edit.length - 1; i >= 0; i--) {
            var item = mPayments_Edit[i];
            var removeRow = false;

            switch (item.PaymentType) {
              case "Regular":
              case "AdjustmentFinalBeforeBallon":
                removeRow = true;
                break;             
            }

            if (removeRow) {
              refresh = true;
              mPayments_Edit.splice(i, 1);
            }
          }

          // Refresh Grid
          if (refresh) C_OverridingPayments.gridPayments.VirtualDataRefresh(mPayments_Edit, true);
          break;

        case "PAYMENTSCLEANUP":
          mOptions.onAction("PaymentsCleanup");
          break;

        default:
          window.alert("Unhandled grid action '" + actionId + "'.");
          break;
      }
    }

    // Handle Actions
    function showOverridingPayments_Action(actionId) {
      switch (actionId) {
        case "Cancel":
          mForm_OverridingPayments.Close();
          break;

        case "Ok":
          showOverridingPayments_Action_Ok();
          break;

        default:
          window.alert(actionId);
      }
    }

    function showOverridingPayments_Action_Ok() {
      // Clean up grid and collection (e.g., rows that we can pretty much guarantee the user doesn't want)
      for (var i = mPayments_Edit.length - 1; i >= 0; i--) {
        // Row required removing?
        var item = mPayments_Edit[i];
        var remove = false;
        if (!item.Date && !item.DateRange && !item.Value) {
          remove = true;
        }

        // Remove
        if (remove) C_OverridingPayments.gridPayments.RemoveRowAndCollectionItem(i);
      }

      // Validate
      var Ok = widget.UI.ValidateContainer(mForm_OverridingPayments.ContentElement());

      // Finalise
      if (Ok) {
        // Replace Overriding Payments
        mPayments = [];
        for (var i = 0; i < mPayments_Edit.length; i++) {
          mPayments.push(mPayments_Edit[i]);
        }

        // Recalculate and Refresh
        OnChange();

        // Close
        mForm_OverridingPayments.Close();
      }
    }

    // ---------------------
    // Show Payment Schedule
    // ---------------------
    function showPaymentSchedule() {
      // Reset
      mCumulativeTotal = 0;

      // Create Modal
      mForm_PaymentSchedule = widget.UI.Modal({
        title: "Payment Schedule",
        width: "90%",
        height: "95%",
        maxWidth: 800,
        maxHeight: 1400,
        minWidth: 400,
        minHeight: 400,

        onAction: showPaymentSchedule_Action,
      });

      // Actions
      //mForm_PaymentSchedule.Actions().Define([{ groupId: "[buttons]", actionId: "Cancel", caption: "Close" }]);

      // Define HTML Content
      var content = "";
      content += "<div class='is-widget-form-body' style='position: absolute; top: 0; left: 0; right: 0; bottom: 0;'>";

      // Show (content will be set in the next block)
      mForm_PaymentSchedule.Show({ content: content });

      // Render
      var e = $("div", mForm_PaymentSchedule.ContentElement());

      // Controls
      e.append("<div class='payment-schedule-grid'></div>");
      C_PaymentSchedule.gridPaymentSchedule = widget.UI.Grid($(".payment-schedule-grid", e), {
        stickyHeader: true,
        rowNumbering: true,

        onInitialiseRow: gridPaymentSchedule_InitialiseRow,
      });

      // Add Columns
      C_PaymentSchedule.gridPaymentSchedule.ClearColumns();
      C_PaymentSchedule.gridPaymentSchedule.AddColumnIcon("Icon", {});
      C_PaymentSchedule.gridPaymentSchedule.AddColumnString("Type", { caption: "Type" });
      C_PaymentSchedule.gridPaymentSchedule.AddColumnDate("Date", { caption: "Date" });
      C_PaymentSchedule.gridPaymentSchedule.AddColumnString("Reference", { caption: "Reference" });
      C_PaymentSchedule.gridPaymentSchedule.AddColumnCurrency("Value", { caption: "Value" });
      C_PaymentSchedule.gridPaymentSchedule.AddColumnCurrency("TotalPayments", { caption: "Total Payments" });
      C_PaymentSchedule.gridPaymentSchedule.AddColumnString("Notes", { caption: "Notes" });

      // Refresh
      C_PaymentSchedule.gridPaymentSchedule.VirtualDataRefresh(mRecord.PaymentSchedule.Items);
    }

    function gridPaymentSchedule_InitialiseRow(e) {
      var item = mRecord.PaymentSchedule.Items[e.row.listIndex];
      var value = (item.Value * -1);

      // Update Cumulative Total
      mCumulativeTotal += value;

      // Update cells
      e.row.cells.Icon.value = item.Icon;
      e.row.cells.Type.value = item.ScheduleTypeText;
      e.row.cells.Date.value = item.Date;
      e.row.cells.Reference.value = item.Reference;
      e.row.cells.Value.value = value;
      e.row.cells.TotalPayments.value = mCumulativeTotal;
      e.row.cells.Notes.value = item.Notes;
    }

    // Handle Actions
    function showPaymentSchedule_Action(actionId) {
      switch (actionId) {
        case "Cancel":
          mForm_PaymentSchedule.Close();
          break;

        default:
          window.alert(actionId);
      }
    }

    //// ------------------
    //// PUBLIC: Initialise
    //// ------------------
    //function Initialise(accountCalc, options) {
    //  //TODO: not currently using this method, using FromJsonString
    //  // Extend options with defaults
    //  var InitialiseDefaults = {
    //    applyDefaultPaymentMethod: false,
    //    applyDefaultCashRegister: false,

    //    defaultValuesOnPaymentMethodChange: false,
    //  };
    //  options = $.extend({}, InitialiseDefaults, options);

    //  // Initialise
    //  mAccountCalc = accountCalc;
    //  mInitialised = true;
    //  UpdateElement(false);

    //  // Get Initialisation details
    //}

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      C.dateOpeningDate.Focus();
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -------------------------
    // PUBLIC: ReadOnly property
    // -------------------------
    function ReadOnly(value) {
      if (value === undefined) {
        // Get
        return mOptions.readOnly;
      }
      else {
        // Set
        if (value != mOptions.readOnly) {
          mOptions.readOnly = value;

          UpdateElement();
        }
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Id of an overriding Standard Transaction Edit HTML Widget to use
    // ------------------------------------------------------------------------
    function StdTransWidgetId(value) {
      if (value === undefined) {
        // Get
        return mOptions.stdTransWidgetId;
      }
      else {
        // Set
        mOptions.stdTransWidgetId = value;
      }
    }

    // ------------------------------------------------------------------------
    // PUBLIC: Update values from a JSON formatted finAccountCalcDetails object
    // ------------------------------------------------------------------------
    function FromAccountCalcJson(json, ownerClientIds, restructureAccountId, restructureBalanceOverdue) {
      // Initialise
      mStdTransactionOwnerClientIds = ownerClientIds;

      // Parse
      var o;
      try {
        o = JSON.parse(json);
      }
      catch (ex) {
        console.warn("widget.UI.AccountFinancial.FromAccountCalcJson: " + ex);
      }

      if (o) {
        mRecord = o;

        // Configuration
        if (o.Config) {
          mConfig = o.Config;

          // Term
          C.cboTermCycle.ListFromCsvString(mConfig.TermList);
          C.cboTermCycle.LimitToList(mConfig.TermLimitToList);

          // Payments
          C.cboPaymentCycle.ListFromCsvString(mConfig.PaymentCycleList);
          C.cboPaymentCycle.LimitToList(mConfig.PaymentCycleLimitToList);
          C.cboPaymentFirstDatePeriod.ListFromCsvString(mConfig.PaymentFirstPeriodList);

          if (!mOptions.isRestructure && mConfig.OptionAllowRegularPayment) {
            if (mConfig.OptionInterestFlatRate) {
              C.numPaymentRegular.ReadOnly(true);
            }
            else {
              C.numPaymentRegular.ReadOnly(false);
            }
          }

          C.cboPaymentFirstDatePeriod.VisibleRow(mConfig.OptionAllowFirstPaymentDate);
          C.datePaymentFirstDate.VisibleRow(mConfig.OptionAllowFirstPaymentDate && !mOptions.isRestructure);
          C.numPaymentRegular.VisibleRow(mConfig.OptionAllowRegularPayment);
          C.numPaymentBalloon.VisibleRow(mConfig.OptionAllowBalloonPayment);

          // Residual
          C.lblResidualValue.VisibleRow(mConfig.OptionAllowResidualValue);
          C.numResidualValue.VisibleRow(mConfig.OptionAllowResidualValue);

          // Credit Limits
          if (mConfig.CreditLimitCount == 0) {
            C.lblCreditLimit.VisibleRow(false);
            C.numCreditLimit1.VisibleRow(false);
            C.numCreditLimit2.VisibleRow(false);
            C.numCreditLimit3.VisibleRow(false);
          }
          else if (mConfig.CreditLimitCount == 1) {
            C.lblCreditLimit.Text("Credit Limit");
            C.lblCreditLimit.VisibleRow(true);
            C.numCreditLimit1.VisibleRow(true);
            C.numCreditLimit2.VisibleRow(false);
            C.numCreditLimit3.VisibleRow(false);            
          }
          else {
            C.lblCreditLimit.Text("Credit Limits");
            C.lblCreditLimit.VisibleRow(true);
            C.numCreditLimit1.VisibleRow(true);
            C.numCreditLimit2.VisibleRow(mConfig.CreditLimitCount > 1);
            C.numCreditLimit3.VisibleRow(mConfig.CreditLimitCount > 2);
          }
          C.numCreditLimit1.Caption(mConfig.CreditLimit1Description + ":");
          C.numCreditLimit2.Caption(mConfig.CreditLimit2Description + ":");
          C.numCreditLimit3.Caption(mConfig.CreditLimit3Description + ":");

          if (mConfig.CreditLimitCount > 0) {
            C.numCreditLimit1.AllowBlank(!mConfig.CreditLimit1Required);
            C.numCreditLimit1.BlankIfZero(mConfig.CreditLimit1Required);
          }
          if (mConfig.CreditLimitCount > 1) {
            C.numCreditLimit2.AllowBlank(!mConfig.CreditLimit2Required);
            C.numCreditLimit2.BlankIfZero(mConfig.CreditLimit2Required);
          }
          if (mConfig.CreditLimitCount > 2) {
            C.numCreditLimit3.AllowBlank(!mConfig.CreditLimit3Required);
            C.numCreditLimit3.BlankIfZero(mConfig.CreditLimit3Required);
          }

          // Minimum Payments
          if (mConfig.OptionAllowMinimumPayment) {
            C.lblMinimumPayments.VisibleRow(true);
            C.cboMinimumPaymentBasis.VisibleRow(true);
            C.cboMinimumPaymentBasis.ListFromCollection(mConfig.MinimumPaymentBasisList, "Description");
            C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
            C.cboMinimumPaymentHoldToPeriod.ListFromCsvString(mConfig.MinimumPaymentHoldToList);
            C.cboMinimumPaymentHoldToPeriod.LimitToList(mConfig.MinimumPaymentHoldToLimitToList);
            C.numMinimumPaymentDueDays.VisibleRow(mConfig.OptionAllowMinimumPaymentDueDays);
            C.chkMinimumPaymentDueDaysOverride.VisibleRow(mConfig.OptionAllowMinimumPaymentDueDays);
          }
          else {
            C.lblMinimumPayments.VisibleRow(false);
            C.cboMinimumPaymentBasis.VisibleRow(false);
            C.numMinimumPaymentValue.VisibleRow(false);
            C.numMinimumPaymentPercent.VisibleRow(false);
            C.cboMinimumPaymentHoldToPeriod.VisibleRow(false);
            C.numMinimumPaymentDueDays.VisibleRow(false);
            C.chkMinimumPaymentDueDaysOverride.VisibleRow(false);
          }
          C.dateMinimumPaymentInstalmentEndDate.VisibleRow(false);
          C.numMinimumPaymentInstalmentResidualValue.VisibleRow(false);          

          // Tax Category
          if (mConfig.OptionAllowTaxCategory) {
            C.cboTaxCategory.RefreshFromStandardRange("TaxCategories");
          }

          // Interest
          C.cboInterestCycle.ListFromCsvString(mConfig.InterestCycleList);
          C.cboInterestCycle.LimitToList(mConfig.InterestCycleLimitToList);
          C.cboInterestPaymentType.ListFromCollection(mConfig.InterestPaymentTypeList, "Description");
          if (mConfig.InterestNegativeRateAllow) {
            C.numInterestRate.MinValue(-9999);
          }
          else {
            C.numInterestRate.MinValue(0);
          }

          if (mConfig.OptionAllowTotalInterest) {
            C.numInterestRate.ButtonsDefine([{ id: "TotalInterest", tooltipText: "Calculate Interest Rate from Total Interest", icon: "Calculator" }]);
          }
          else {
            C.numInterestRate.ButtonsDefine([]);
          }

          // Start-up Interest
          if (mConfig.OptionAllowStartupInterest) {
            C.lblStartupInterestRate.VisibleRow(true);
            C.cboStartupInterestType.ListFromCollection(mConfig.StartupInterestTypeList, "Description");
            C.cboStartupInterestType.VisibleRow(true);
            C.cboStartupInterestPeriod.ListFromCsvString(mConfig.StartupInterestPeriodList);
            C.cboStartupInterestPeriod.LimitToList(mConfig.StartupInterestPeriodLimitToList);
            C.cboStartupInterestRateTable.RefreshFromStandardRange("RateTables", mConfig.StartupRateTableFilter);
            C.cboStartupInterestRateTable.BlankTip(mConfig.StartupStandardRateTableId);
            C.cboStartupInterestRateTable.AllowBlank(mConfig.StartupStandardRateTableId != "");
          }
          else {
            C.lblStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestType.VisibleRow(false);
            C.cboStartupInterestPeriod.VisibleRow(false);
            C.numStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestRateTable.VisibleRow(false);
            C.numStartupInterestRatePremium.VisibleRow(false);
            C.numStartupInterestRateBase.VisibleRow(false);
            C.dateStartupInterestToDate.VisibleRow(false);
          }

          // Interest Rate
          C.cboInterestType.ListFromCollection(mConfig.InterestTypeList, "Description");
          C.cboInterestRateTable.RefreshFromStandardRange("RateTables", mConfig.RateTableFilter);
          C.cboInterestRateTable.BlankTip(mConfig.StandardRateTableId);
          C.cboInterestRateTable.AllowBlank(mConfig.StandardRateTableId != "");

          // Other Interest
          if (mConfig.OtherInterestCaption) C.lblOtherInterest.Text(mConfig.OtherInterestCaption);
          C.lblOtherInterest.VisibleRow(mConfig.OtherInterestShow);
          C.numOtherInterestRate.VisibleRow(mConfig.OtherInterestShow);

          // Enhance lists
          widget.ArrayToCodeDescriptionList(mConfig.AccountCalcPaymentTypeList);
        }
        else {
          mConfig = {};
          console.warn("widget_ui.AccountFinancial: FromAccountCalcJson does not contain a Config object to enable configuration such as Term Entry Method");
        }

        // Restructure
        if (mOptions.isRestructure) {
          // Restructure Account
          if (restructureAccountId) {
            mRecord.AccountId = restructureAccountId;
          }

          // Overdue
          if (restructureBalanceOverdue) {
            mRecord.RestructureBalanceOverdue = restructureBalanceOverdue;
          }
          else {
            mRecord.RestructureBalanceOverdue = 0;
          }

          // Hold to Maturity Date
          if (o.RestructureDate > o.DateMaturity) {
            C.chkHoldToOriginalMaturityDate.VisibleRow(false);
          }
          else {
            C.chkHoldToOriginalMaturityDate.VisibleRow(true);
          }

          // Other Controls
          C.datePaymentNextDate.Value(o.PaymentNextDate);
          chkHoldFinalPaymentDate_Change();
          chkByNumberofPayments_Change();
        }        

        // Term
        C.dateOpeningDate.Value(o.OpeningDate);
        C.cboTermCycle.Text(o.TermCycle);
        cboTermCycle_Change();
        C.dateTermCycleOnDate.Value(o.TermCycleOnDate);
        C.numTermNumberOfPayments.Value(o.TermNumberOfPayments);
        C.dateMaturityDate.Value(o.DateMaturity);
        dateMaturityDate_Change();

        // Minimum Payments
        C.cboMinimumPaymentBasis.Text(o.MinimumPaymentBasisText);
        cboMinimumPaymentBasis_Change();
        C.numMinimumPaymentDueDays.Value(o.MinimumPaymentDueDays);
        C.chkMinimumPaymentDueDaysOverride.Value(o.MinimumPaymentDueDaysOverride);
        chkMinimumPaymentDueDaysOverride_Change();
        C.numMinimumPaymentValue.Value(o.MinimumPaymentValue);
        C.numMinimumPaymentPercent.Value(o.MinimumPaymentPercent);
        C.cboMinimumPaymentHoldToPeriod.Text(o.MinimumPaymentHoldToPeriod);
        cboMinimumPaymentHoldToPeriod_Change();
        C.dateMinimumPaymentInstalmentEndDate.Value(o.MinimumPaymentInstalmentEndDate);
        C.numMinimumPaymentInstalmentResidualValue.Value(o.MinimumPaymentInstalmentResidualValue);
        C.dateMinimumPaymentHoldToDate.Value(o.MinimumPaymentHoldToDate);

        // Payments
        C.cboPaymentCycle.Text(o.PaymentCycle);
        C.cboPaymentFirstDatePeriod.Text(o.PaymentFirstDatePeriod);
        cboPaymentFirstDatePeriod_Change();
        C.datePaymentFirstDate.Value(o.PaymentFirstDate);
        dateOpeningDate_Change(); // Sync First Payment Date if necessary
        C.numPaymentRegular.BlankTip(widget.FormatCurrency(o.PaymentRegular));
        if (o.PaymentRegularOverride != 0) {
          C.numPaymentRegular.Value(o.PaymentRegularOverride);
        }
        else {
          C.numPaymentRegular.Value(null);
        }

        // Override for Restructure
        if (mOptions.isRestructure && o.IsRestructureCalculation && o.PaymentRegular) {
          C.numPaymentRegular.Value(o.PaymentRegular);
        }

        // Other Restructure options
        if (mOptions.isRestructure && o.IsRestructureCalculation) {
          C.datePaymentFinalDate.Value(o.PaymentFinalDateHoldDate);
          C.numNumberofPayments.Value(o.PaymentFinalDateHoldNumberPayments);

          if (!o.PaymentFinalDateHold) {
            C.chkHoldToOriginalMaturityDate.Value(false);
            C.chkHoldFinalPaymentDate.Value(false);
            C.chkByNumberofPayments.Value(false);
          }
        }

        numPaymentRegular_Change();
        C.numPaymentBalloon.Value(o.PaymentBalloon);

        // Residual
        C.numResidualValue.Value(o.ResidualValue);

        // Credit Limit
        C.numCreditLimit1.Value(o.CreditLimit1);
        C.numCreditLimit2.Value(o.CreditLimit2);
        C.numCreditLimit3.Value(o.CreditLimit3);

        // Tax Category
        C.cboTaxCategory.Text(o.TaxCategoryId);

        // Interest
        C.cboInterestCycle.Text(o.InterestCycle);
        cboInterestCycle_Change();
        C.dateInterestCycleDateFirst.Value(o.InterestCycleDateFirst);
        C.cboInterestPaymentType.Text(o.InterestPaymentTypeText);
        cboInterestType_Change();

        // Startup Interest
        C.cboStartupInterestType.Text(o.StartupInterestTypeText);
        cboStartupInterestType_Change();
        C.cboStartupInterestPeriod.Text(o.StartupInterestPeriod);
        cboStartupInterestPeriod_Change();
        C.dateStartupInterestToDate.Value(o.StartupInterestToDate);
        C.numStartupInterestRate.Value(o.StartupInterestRate);
        C.cboStartupInterestRateTable.Text(o.StartupInterestRateTableId);
        C.numStartupInterestRatePremium.Value(o.StartupInterestRatePremium);
        C.numStartupInterestRateBase.Value(o.StartupInterestRateBase);

        // Interest Rate
        C.cboInterestType.Text(o.InterestTypeText);
        C.numInterestRate.Value(o.InterestRate);
        C.cboInterestRateTable.Text(o.InterestRateTableId);
        C.numInterestRatePremium.Value(o.InterestRatePremium);
        C.numInterestRateBase.Value(o.InterestRateBase);

        // Other Interest
        C.numOtherInterestRate.Value(o.OtherInterestRate);

        // Advanced Button
        if (C.cmdAdvanced) {
          if (mConfig.OptionShowFinancialPageOptionsTab) {
            C.cmdAdvanced.show();

            // Update Charge Interest on Interest controls
            UpdateInterestOnInterestVisibility();
          }
          else {
            C.cmdAdvanced.hide();
            C.cmdAdvanced.removeClass("checked");
            mOptions.advancedVisible = false;
            C.divAdvanced.hide();
          }
        }

        // Advanced: Default Interest
        C.cboDefaultInterestRateBasis.ListFromCsvString(mConfig.DefaultInterestRateBasisList);
        C.cboDefaultInterestRateBasis.Text(o.DefaultInterestRateBasisText);
        C.numDefaultInterestRate.Value(o.DefaultInterestRate);

        // Advanced: Interest Rate change instructions
        C.cboInterestInstructionDown.ListFromCsvString(mConfig.InterestInstructionDownList);
        C.cboInterestInstructionDown.Text(o.InterestInstructionDownText);
        C.cboInterestInstructionUp.ListFromCsvString(mConfig.InterestInstructionUpList);
        C.cboInterestInstructionUp.Text(o.InterestInstructionUpText);

        // Advanced: Options
        C.chkPaymentsInAdvance.Value(o.OptionPaymentsInAdvance);
        C.chkOptionPaymentsFinalPlusBalloon.Value(o.OptionPaymentsFinalPlusBalloon);
        C.chkOptionInterestOnInterest.Value(o.OptionInterestOnInterest);
        C.cboOptionPaymentAllocationMethod.ListFromCsvString(mConfig.OptionPaymentAllocationMethodList);
        C.cboOptionPaymentAllocationMethod.Text(o.OptionPaymentAllocationMethodText);

        // Update
        UpdateElement();

        // Standard Transactions
        if (mOptions.showStdTrans) {
          if (C.gridStdTrans.Editing()) {
            // Don't interfere with current edit operation
            var t = window.setInterval(function () {
              if (C.gridStdTrans.Editing()) {
                // Still editing!
              }
              else {
                // Not editing
                window.clearInterval(t);
                t = null;
                C.gridStdTrans.VirtualDataRefresh(o.StdTrans, true);
              }
            }, 100);
          }
          else {
            C.gridStdTrans.VirtualDataRefresh(o.StdTrans, true);
            if (mEditStandardTransactionIndex == -1) {
              C.gridStdTrans.ActivateLastDataRow(true);
            }
            else {
              C.gridStdTrans.ActivateFirstDataRow(true);
            }
          }
        }

        // Payments
        mPayments = o.Payments;
      }
    }

    // -----------------------------------
    // PUBLIC: Get a finAccountCalc object
    // -----------------------------------
    function ToAccountCalc() {
      var o = {};

      // Preserve non-field information
      // NOTE: E.g., AccountTypeIdOriginal which is used to test changes in Account Type to reset Standard Transactions
      if (mRecord) {
        o = JSON.parse(JSON.stringify(mRecord));

        // Clear special fields
        o.FieldUpdated = "";
      }

      // Restructure Details
      if (mOptions.isRestructure) {
        o.PaymentFinalDateHold = false;
        o.PaymentFinalDateHoldDate = null;
        o.PaymentFinalDateHoldNumberPayments = null;

        if (C.chkHoldToOriginalMaturityDate.Value()) {
          o.PaymentFinalDateHold = true;
          o.PaymentFinalDateHoldDate = C.dateMaturityDate.Value();
        }
        else if (C.chkHoldFinalPaymentDate.Value()) {
          o.PaymentFinalDateHold = true;
          o.PaymentFinalDateHoldDate = C.datePaymentFinalDate.Value();
        }
        else if (C.chkByNumberofPayments.Value()) {
          o.PaymentFinalDateHold = true;
          o.PaymentFinalDateHoldNumberPayments = C.numNumberofPayments.Value();
        }
        o.PaymentNextDate = C.datePaymentNextDate.Value();
      }

      // Term
      o.OpeningDate = C.dateOpeningDate.Value();
      o.TermCycle = C.cboTermCycle.Text();
      o.TermCycleOnDate = C.dateTermCycleOnDate.Value();
      o.TermNumberOfPayments = C.numTermNumberOfPayments.Value();
      o.DateMaturity = C.dateMaturityDate.Value();

      // Minimum Payments
      o.MinimumPaymentBasisText = C.cboMinimumPaymentBasis.Text();
      o.MinimumPaymentDueDays = C.numMinimumPaymentDueDays.Value();
      o.MinimumPaymentDueDaysOverride = C.chkMinimumPaymentDueDaysOverride.Value();
      o.MinimumPaymentValue = C.numMinimumPaymentValue.Value();
      o.MinimumPaymentPercent = C.numMinimumPaymentPercent.Value();
      o.MinimumPaymentHoldToPeriod = C.cboMinimumPaymentHoldToPeriod.Text();
      o.MinimumPaymentHoldToDate = C.dateMinimumPaymentHoldToDate.Value();
      o.MinimumPaymentInstalmentEndDate = C.dateMinimumPaymentInstalmentEndDate.Value();
      o.MinimumPaymentInstalmentResidualValue = C.numMinimumPaymentInstalmentResidualValue.Value();

      // Payments
      o.PaymentCycle = C.cboPaymentCycle.Text();
      o.PaymentFirstDatePeriod = C.cboPaymentFirstDatePeriod.Text();
      o.PaymentFirstDate = C.datePaymentFirstDate.Value();      
      o.PaymentRegularOverride = C.numPaymentRegular.Value();
      o.PaymentBalloon = C.numPaymentBalloon.Value();

      // Residual
      o.ResidualValue = C.numResidualValue.Value();

      // Credit Limit
      o.CreditLimit1 = C.numCreditLimit1.Value();
      o.CreditLimit2 = C.numCreditLimit2.Value();
      o.CreditLimit3 = C.numCreditLimit3.Value();

      // Tax Category
      o.TaxCategoryId = C.cboTaxCategory.Text();

      // Interest
      o.InterestCycle = C.cboInterestCycle.Text();
      o.InterestCycleDateFirst = C.dateInterestCycleDateFirst.Value();
      o.InterestPaymentTypeText = C.cboInterestPaymentType.Text();

      // Startup Interest
      o.StartupInterestTypeText = C.cboStartupInterestType.Text();
      o.StartupInterestPeriod = C.cboStartupInterestPeriod.Text();
      o.StartupInterestToDate = C.dateStartupInterestToDate.Value();
      o.StartupInterestRate = C.numStartupInterestRate.Value();
      o.StartupInterestRateTableId = C.cboStartupInterestRateTable.Text();
      o.StartupInterestRatePremium = C.numStartupInterestRatePremium.Value();

      // Interest Rate
      o.InterestTypeText = C.cboInterestType.Text();
      o.InterestRate = C.numInterestRate.Value();
      o.InterestRateTableId = C.cboInterestRateTable.Text();
      o.InterestRatePremium = C.numInterestRatePremium.Value();

      // Other Interest
      o.OtherInterestRate = C.numOtherInterestRate.Value();

      // Advanced: Default Interest
      o.DefaultInterestRateBasisText = C.cboDefaultInterestRateBasis.Text();
      o.DefaultInterestRate = C.numDefaultInterestRate.Value();

      // Advanced: Interest Rate change instructions
      o.InterestInstructionDownText = C.cboInterestInstructionDown.Text();
      o.InterestInstructionUpText = C.cboInterestInstructionUp.Text();

      // Advanced: Options
      o.OptionPaymentsInAdvance = C.chkPaymentsInAdvance.Value();
      o.OptionPaymentsFinalPlusBalloon = C.chkOptionPaymentsFinalPlusBalloon.Value();
      o.OptionInterestOnInterest = C.chkOptionInterestOnInterest.Value();
      o.OptionPaymentAllocationMethodText = C.cboOptionPaymentAllocationMethod.Text();

      // Standard Transactions
      o.StdTrans = mRecord.StdTrans;

      // Payments
      o.Payments = JSON.parse(JSON.stringify(mPayments));

      // Other
      o.IsRestructureCalculation = mOptions.isRestructure;

      return o;
    }

    // --------------------------------------------------
    // PUBLIC: Get a JSON formatted finAccountCalc object
    // --------------------------------------------------
    function ToAccountCalcJson() {
      return JSON.stringify(ToAccountCalc());
    }

    // ----------------------------------------------
    // PUBLIC: Get Interest Payment Type (enum value)
    // ----------------------------------------------
    function InterestPaymentType() {
      // NOTE: This shortcuts getting the actual enum value by simply removing spaces and handling U.S spelling
      var s = C.cboInterestPaymentType.Text().replace(" ", "");
      if (s == "Check") s = "Cheque";

      return s;
    }

    // ------------------------
    // PUBLIC: Get Opening Date
    // ------------------------
    function OpeningDate() {
      return C.dateOpeningDate.Value();
    }

    // ----------------------
    // PUBLIC: Get Term Cycle
    // ----------------------
    function TermCycle() {
      return C.cboTermCycle.Text();
    }

    // -------------------------
    // PUBLIC: Get Payment Cycle
    // -------------------------
    function PaymentCycle() {
      return C.cboPaymentCycle.Text();
    }

    // -----------------------------
    // PUBLIC: Get Payment Next Date
    // -----------------------------
    function PaymentNextDate() {
      return C.datePaymentNextDate.Value();
    }

    // ----------------
    // PUBLIC: Promises
    // ----------------
    function Promises() {
      if (mPromises) {
        return JSON.parse(JSON.stringify(mPromises));
      }
      else {
        return [];
      }      
    }

    // ----------------------
    // PUBLIC: Clear Promises
    // ----------------------
    function PromisesClear() {
      mPromises = [];
    }

    // -------------------------------
    // PUBLIC: Set Overriding Payments
    // -------------------------------
    function SetOverridingPayments(payments) {
      // Update Payments
      mPayments_Edit = JSON.parse(JSON.stringify(payments));

      // Refresh Grid
      C_OverridingPayments.gridPayments.VirtualDataRefresh(mPayments_Edit, true);
    }

    // ---------------------------------------------------
    // PUBLIC: Sets if this Calculation is for a Refinance
    // ---------------------------------------------------
    function SetRefinance(isRefinance) {
      if (isRefinance === null) isRefinance = false;

      // Update
      mOptions.isRefinance = isRefinance;

      // Update Controls
      UpdateElement();
    }

    // -------------------------------
    // PUBLIC: Get Overriding Payments
    // -------------------------------
    function GetOverridingPaymentsJson() {
      return JSON.stringify(mPayments_Edit);
    }

    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self = {
      TypeName: "AccountFinancial",      
      
      Focus: Focus,
      
      ReadOnly: ReadOnly,
      StdTransWidgetId: StdTransWidgetId,
      Visible: Visible,

      SetAccountId: SetAccountId,
      FromAccountCalcJson: FromAccountCalcJson,
      ToAccountCalc: ToAccountCalc,
      ToAccountCalcJson: ToAccountCalcJson,

      OpeningDate: OpeningDate,
      InterestPaymentType: InterestPaymentType,
      TermCycle: TermCycle,
      PaymentCycle: PaymentCycle,
      PaymentNextDate: PaymentNextDate,
      Promises: Promises,
      PromisesClear: PromisesClear,

      GetOverridingPaymentsJson: GetOverridingPaymentsJson,
      SetOverridingPayments: SetOverridingPayments,

      SetRefinance: SetRefinance,
    };
    return _self;
  }



  // =============================
  // PUBLIC: Table Filter Text Box
  // =============================
  function TableFilterTextBox(e, options) {

    var mFilterCountLabel;
    var mFilterTables;
    var mFilterText;
    var mGrid;
    var mOptions;
    var mTextBox;
    var mTimer;

    // Extend options with defaults
    TableFilterTextBoxDefaults = {
      autoReadOnly: false,
      maxLength: 20,
      blankTip: "Type to filter list",
      restrictToTbody: true,
      showFilterCount: true,
      applyFilteredInClass: false,
      visible: true,

      onFilterApplied: null,
    };
    mOptions = $.extend({}, TableFilterTextBoxDefaults, options);

    // Always read-only until initialised
    mOptions.readOnly = true;

    // Create TextBox
    mTextBox = widget.UI.TextBox(e, options);

    // Filter Count Label
    if (mOptions.showFilterCount) {
      mFilterCountLabel = $("<div class='is-table-filter-count' style='display:none'></div>");
      mFilterCountLabel.click(function () { mTextBox.Focus(); mTextBox.Text(""); ApplyFilter(mTextBox.Text()); });
      mTextBox.Element().after(mFilterCountLabel);
      mTextBox.Element().addClass("is-has-table-filter-count");
    }

    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Visible
      if (mOptions.visible) {
        mTextBox.Visible(true);
      }
      else {
        mTextBox.Visible(false);
      }
    }

    // -----------------------------------------
    // PUBLIC: Initialise, i.e., attach table(s)
    // -----------------------------------------
    function Initialise(filterTables) {
      mGrid = null;
      mFilterTables = filterTables;
      mFilterText = "";
      if (mFilterCountLabel) mFilterCountLabel.hide();

      // Apply filter at an interval
      if (mTimer) window.clearInterval(mTimer);
      mTimer = window.setInterval(function () {
        if (mTextBox.Text() != mFilterText) {
          ApplyFilter(mTextBox.Text());
        }
      }, 200);

      // Finalise
      mTextBox.ReadOnly(false);
    }

    // -----------------------------
    // PUBLIC: Initialise for a Grid
    // -----------------------------
    function InitialiseGrid(grid) {
      Initialise($("table", grid.Element()));
      mGrid = grid;
    }

    // ----------------------
    // PUBLIC: Reapply filter
    // ----------------------
    function ReapplyFilter() {
      ApplyFilter(mFilterText);
    }

    // --------------------
    // PUBLIC: Apply filter
    // --------------------
    function ApplyFilter(filterText) {
      var hasRowSelector = false;

      mFilterText = filterText;
      mFilteredOutCount = 0;

      // Clear all filters
      if (mOptions.restrictToTbody) {
        $("tbody > tr", mFilterTables).removeClass("is-filtered-out is-filtered-in");
      }
      else {
        $("tr", mFilterTables).removeClass("is-filtered-out is-filtered-in");
      }
      if (mFilterCountLabel) mFilterCountLabel.hide();

      if (mFilterText) {
        // Split filter criteria
        var criteria = mFilterText.toUpperCase().split(" ");
        if (criteria.length > 0) {
          // Get all rows (except template row in editable grids)
          var rows;
          if (mOptions.restrictToTbody) {
            rows = $("tbody > tr:not(.templaterow)", mFilterTables);
          }
          else {
            rows = $("tr", mFilterTables);
          }

          for (var i = 0; i < rows.length; i++) {
            // Get row
            var row = rows[i];

            // Has row selector?
            if (i == 0) {
              var rc = $("td,th", row);

              if (rc.length > 1) {
                if ($(rc[0]).hasClass("rowselector")) {
                  hasRowSelector = true;
                }
              }
            }

            // Check criteria exists (ALL criteria must exist in a row)
            var foundInRecord = true;
            for (var crit = 0; crit < criteria.length; crit++) {
              var critText = criteria[crit];
              var found = false;
              var rowCells;
              if (mOptions.restrictToTbody) {
                rowCells = $("td", row);
              }
              else {
                rowCells = $("td,th", row);
              }

              if (critText && critText != " ") {
                for (var col = hasRowSelector ? 1 : 0; col < rowCells.length; col++) {
                  var colText = $(rowCells[col]).text();

                  if (colText && colText.toUpperCase().indexOf(critText) != -1) {
                    found = true;
                    break;
                  }

                  // For numbers, check the formatted version too, e.g., for "1234", also check "1,234"
                  if (!isNaN(critText)) {
                    // Format
                    critText = Runtime_FormatNumber(parseFloat(critText), 6, true);

                    // Remove trailing zeros and decimal point (if necessary)
                    while (critText.endsWith("0")) {
                      critText = critText.substr(0, critText.length - 1);
                    }
                    if (critText.endsWith(".")) critText = critText.substr(0, critText.length - 1);

                    if (colText && colText.indexOf(critText) != -1) {
                      found = true;
                      break;
                    }
                  }
                }
              }

              if (!found) {
                foundInRecord = false;
                break;
              }
            }

            // Filter row out?
            if (foundInRecord) {
              if (mOptions.applyFilteredInClass) {
                $(rows[i]).addClass("is-filtered-in");
              }
            }
            else {
              mFilteredOutCount += 1;
              $(rows[i]).addClass("is-filtered-out");
            }
          }
        }

        // Update filter count label
        if (mFilterCountLabel) {
          var total = rows.length;
          var groupHeaderRows = 0;

          // Remove group header rows from total (J030634)
          for (var i = 0; i < rows.length; i++) {
            if ($(rows[i]).hasClass("group-header")) groupHeaderRows += 1;
          }

          mFilterCountLabel.text(Runtime_FormatNumber(total - mFilteredOutCount, 0) + " of " + Runtime_FormatNumber(total - groupHeaderRows, 0));
          mFilterCountLabel.show();
        }
      }

      // Notify
      if (mOptions.onFilterApplied) {
        mOptions.onFilterApplied();
      }

      // Notify Grid, e.g., so it can resize headers that may have changed
      if (mGrid) mGrid.NotifyTableFilterApplied();
    }

    // --------------------------
    // PUBLIC: Filtered Out Count
    // --------------------------
    function FilteredOutCount() {
      return mFilteredOutCount;
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "TableFilterTextBox",

      Initialise: Initialise,
      InitialiseGrid: InitialiseGrid,
      FilteredOutCount: FilteredOutCount,

      ApplyFilter: ApplyFilter,
      ReapplyFilter: ReapplyFilter,

      /* From TextBox */
      AutoReadOnly: mTextBox.AutoReadOnly,
      BlankTip: mTextBox.BlankTip,
      Element: mTextBox.Element,
      Focus: mTextBox.Focus,
      HasFocus: mTextBox.HasFocus,
      ReadOnly: mTextBox.ReadOnly,
      Text: mTextBox.Text,
      Visible: Visible,
      VisibleRow: mTextBox.VisibleRow,
      WidthResizeFromParent: mTextBox.WidthResizeFromParent
    };

    return _self;
  }



  // ==========================
  // PUBLIC: Compare Items Grid
  // ==========================
  function CompareItemsGrid(e, options) {

    var mCompareItems;
    var mElement;
    var mGrid;
    var mOptions;

    // Extend options with defaults
    CompareItemsGridDefaults = {
      visible: true,
    };
    mOptions = $.extend({}, CompareItemsGridDefaults, options);

    // Get Element and validate (may be element or id)
    var id;
    if (typeof e == "string") {
      id = e;
      e = $("#" + id);
    }
    else {
      id = $(e).attr("id");
    }
    var el = $(e);
    if (el.length == 0) {
      console.warn("widget_ui.CompareItemsGrid: Element '" + id + "' not found.");
      return;
    }
    mElement = $(el[0]);

    // Create Grid
    mGrid = widget.UI.Grid(mElement, {
      stickyHeader: true,
      showRowSelectors: true,
      allowMultiRowSelect: true,

      onAction: mGrid_Action,
      onBeforeCellUpdate: mGrid_BeforeCellUpdate,
      onInitialiseRow: mGrid_InitialiseRow,
    });


    // Initialise
    UpdateElement();


    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Visible
      if (mOptions.visible) {
        mElement.show();
      }
      else {
        mElement.hide();
      }
    }

    // --------------------------------------------------
    // PUBLIC: Refresh with a collection of Compare Items
    // --------------------------------------------------
    function Refresh(compareItems, showGroupColumn, value1Caption, value2Caption) {
      // Initialise
      mCompareItems = compareItems;
      showGroupColumn = (showGroupColumn == true);
      if (!value1Caption) value1Caption = "Value 1";
      if (!value2Caption) value2Caption = "Value 2";

      // Add Columns
      mGrid.ClearColumns();
      mGrid.AddColumnString("GroupKey", { caption: "Group", width: "8em", visible: showGroupColumn });
      mGrid.AddColumnString("Key", { caption: "Key", width: "10%", wrap: true, visible: false });
      mGrid.AddColumnString("Description", { caption: "Item" });
      mGrid.AddColumnString("Value1", { caption: value1Caption, width: "20%", wrap: true, backgroundColour: "lightblue" });
      mGrid.AddColumnString("Value2", { caption: value2Caption, width: "20%", wrap: true, backgroundColour: "orange" });
      mGrid.AddColumnBoolean("Identical", { caption: "Identical", visible: false });
      mGrid.AddColumnBoolean("UseValue2", { caption: "Use", allowEdit: true });
      mGrid.AddColumnString("Updated", { caption: "Updated", width: "20%", wrap: true });

      // Actions
      mGrid.Actions().Define([{ actionId: "SelectUp", tooltipText: "Select all rows above and including the current row", icon: "Select_Up" },
        { actionId: "SelectDown", tooltipText: "Select all rows below and including the current row", icon: "Select_Down" },
        { actionId: "SelectAll", tooltipText: "Select all valid rows", icon: "Select_All" },
        { actionId: "SelectNone", tooltipText: "Select no rows", icon: "Select_None" },
        { actionId: "SelectChecked", tooltipText: "Select all rows that are checked to include", icon: "Select_Checked" },
        { actionId: "SelectUnchecked", tooltipText: "Select all rows that are not checked to include", icon: "Select_Unchecked" },
        { actionId: "SelectGroup", tooltipText: "Select all rows in the current group", icon: "Select_Same" },
        {},
        { actionId: "Check", tooltipText: "Check selected row(s)", icon: "Checkbox_Checked" },
        { actionId: "Uncheck", tooltipText: "Uncheck selected row(s)", icon: "Checkbox_Unchecked" }
      ]);

      // Refresh Grid
      mGrid.VirtualDataRefresh(mCompareItems);
    }

    // ----
    // Grid
    // ----
    function mGrid_InitialiseRow(e) {
      var item = mCompareItems[e.row.listIndex];
      var lastGroupKey = e.row.listIndex > 0 ? mCompareItems[e.row.listIndex - 1].GroupKey : "";

      // Update cells
      e.row.AutoBind(item);

      // Don't repeat Group Key
      if (lastGroupKey == item.GroupKey) e.row.cells.GroupKey.value = "";

      // Updated value
      if (item.AlwaysShow) {
        if (item.Value1 == "") {
          e.row.cells.Updated.value = item.Value2;
          e.row.cells.Updated.backgroundColour = "orange";
        }
        else {
          e.row.cells.Updated.value = item.Value1;
          e.row.cells.Updated.backgroundColour = "lightblue";
        }
      }
      else {
        if (item.UseValue1) {
          e.row.cells.Updated.value = item.Value1;
        }
        else {
          e.row.cells.Updated.value = item.Value2;
        }

        if (item.Value1 == item.Value2) {
          e.row.cells.UseValue2.readOnly = true;
        }
        else {
          e.row.cells.UseValue2.readOnly = false;
          if (item.UseValue1) {
            e.row.cells.Updated.backgroundColour = "lightblue";
            e.row.cells.Updated.bold = false;
          }
          else {
            e.row.cells.Updated.backgroundColour = "orange";
            e.row.cells.Updated.bold = true;
          }
        }
      }

      // Styles
      e.row.cells.GroupKey.bold = true;
      e.row.cells.GroupKey.readOnly = true;
      if (e.row.cells.UseValue2.readOnly) {
        e.row.cells.UseValue2.value = false;
        e.row.cells.Value1.backgroundColour = "#FFF0F0";
        e.row.cells.Value2.backgroundColour = "#FFF0F0";
      }
      e.row.cells.Description.readOnly = true;
      e.row.cells.Updated.readOnly = true;
      e.row.cells.Updated.bold = (item.UseValue2 && (!item.Identical || item.AlwaysShow));

      // Read-Only?
      if (item.ReadOnly) {
        e.row.cells.UseValue2.readOnly = true;
      }

      // Hide row
      if (item.Identical && !item.AlwaysShow) e.row.hidden = true;
    }

    function mGrid_BeforeCellUpdate(e) {
      var item = mCompareItems[e.row.listIndex];

      switch (e.columnKey) {
        case "UseValue2":
          item.UseValue2 = e.newValue;
          item.UseValue1 = !item.UseValue2;

          // Refresh row
          e.refreshRow = true;
          break;
      }
    }

    function mGrid_Action(actionId) {

      switch (actionId.toUpperCase()) {
        case "SELECTGROUP":
          var activeRowIndex = mGrid.ActiveDataRowListIndex();
          var indexes = [];

          if (activeRowIndex != -1) {
            var GroupKey = mCompareItems[activeRowIndex].GroupKey;
            for (var i = 0; i < mCompareItems.length; i++) {
              if (!mCompareItems[i].ReadOnly && mCompareItems[i].GroupKey == GroupKey) {
                indexes.push(i);
              }
            }
          }
          break;

        case "SELECTUP":
        case "SELECTDOWN":
          var activeRowIndex = mGrid.ActiveDataRowListIndex();
          var indexes = [];

          for (var i = 0; i < mCompareItems.length; i++) {
            if (!mCompareItems[i].ReadOnly) {
              if (actionId.toUpperCase() == "SELECTUP" && i <= activeRowIndex) {
                indexes.push(i);
              }
              else if (actionId.toUpperCase() == "SELECTDOWN" && i >= activeRowIndex) {
                indexes.push(i);
              }
            }
          }
          break;

        case "SELECTALL":
          var indexes = [];
          for (var i = 0; i < mCompareItems.length; i++) {
            var item = mCompareItems[i];
            if (!item.ReadOnly) indexes.push(i);
          }
          break;

        case "SELECTNONE":
          var indexes = [];
          break;

        case "SELECTCHECKED":
        case "SELECTUNCHECKED":
          var indexes = [];

          for (var i = 0; i < mCompareItems.length; i++) {
            var item = mCompareItems[i];

            if (!item.ReadOnly) {
              if (actionId.toUpperCase() == "SELECTCHECKED" && item.UseValue2) {
                indexes.push(i);
              }
              else if (actionId.toUpperCase() == "SELECTUNCHECKED" && !item.UseValue2) {
                indexes.push(i);
              }
            }
          }
          break;

        case "CHECK":
        case "UNCHECK":
          var selectedItems = mGrid.GetSelectedRowIndexes(true, true);

          for (var i = 0; i < selectedItems.length; i++) {
            var item = mCompareItems[selectedItems[i]];
            if (!item.ReadOnly) {
              if (actionId.toUpperCase() == "CHECK") {
                item.UseValue2 = true;
              }
              else {
                item.UseValue2 = false;
              }
            }
          }
          mGrid.VirtualDataRefresh(mCompareItems, true, { retainSelectedRows: true });
          break;

        default:
          break;
      }

      // Set Indexes
      if (indexes) {
        mGrid.SetSelectedRowIndexes(indexes, true);
      }
    }

    // ------------------------
    // PUBLIC: Visible property
    // ------------------------
    function Visible(value) {
      if (value === undefined) {
        // Get
        return mOptions.visible;
      }
      else {
        // Set
        mOptions.visible = value;

        // Refresh
        UpdateElement();
      }
    }

    // ------------------------------
    // PUBLIC: Count of checked items
    // ------------------------------
    function CountChecked() {
      var count = 0;

      for (var i = 0; i < mCompareItems.length; i++) {
        var item = mCompareItems[i];
        if (!item.ReadOnly && item.UseValue2) count += 1;
      }

      return count;
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    _self = {
      TypeName: "CompareItemsGrid",

      CountChecked: CountChecked,
      Refresh: Refresh,
      Visible: Visible,
    };

    return _self;
  }

  // ===========================================================================================
  // PUBLIC: Visualise that a Control has Changed, e.g., as the result of a server-side callback
  // ===========================================================================================
  function VisualiseControlChanged(ctl) {
    if (!ctl || !ctl.TypeName) {
      console.warn("widget_ui.VisualiseControlChanged: ctl not specified or does not have a TypeName property.");
      return;
    }

    // Find Element
    var e;
    if (ctl.WrapperElement) {
      e = ctl.WrapperElement();
    }
    else if (ctl.Element) {
      e = ctl.Element();
    }
    else {
      console.warn("widget_ui.VisualiseControlChanged: ctl does not have either an Element or WrapperElement property.");
    }

    // Visualise
    if (e) {
      e.addClass("is-visualise-change in");
      var ti = window.setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        e.removeClass("in");
      }, 1000);
      var ti = window.setTimeout(function () {
        window.clearTimeout(ti);
        ti = null;

        e.removeClass("is-visualise-change");
      }, 2000);
    }
  }

  // =========================================================
  // PUBLIC: Toggle a record's Bookmark from the supplied Tabs
  // =========================================================
  function BookmarkToggleTabs(tabs, recordType, pk, code, description) {
    // Toggle bookmark
    // NOTE: The Web Service calls below may fail but at least this gives a nice responsive interface to the User
    tabs.Bookmarked(!tabs.Bookmarked());

    // Add/ remove bookmark
    if (tabs.Bookmarked()) {
      // Add
      BookmarkAdd(recordType, pk, code, description);
    }
    else {
      // Remove
      BookmarkRemove(recordType, pk);
    }
  }

  // ==============================
  // PRIVATE: Add a record Bookmark
  // ==============================
  function BookmarkAdd(recordType, pk, id, description) {
    widget._SystemGetString("BookmarkAdd", { recordType: recordType, pk: pk, id: id, description: description },
      function (data) {
        // Success
      },

      function (error) {
        // Fail
        widget.RegisterError("widget_ui.BookmarkAdd: Failed to add bookmark: " + error);
      }
    );
  }

  // ================================
  // PRIVATE: Remove a record Bookmark
  // ================================
  function BookmarkRemove(recordType, pk) {
    widget._SystemGetString("BookmarkRemove", { recordType: recordType, pk: pk },
      function (data) {
        // Success
      },

      function (error) {
        // Fail
        widget.RegisterError("widget_ui.BookmarkRemove: Failed to remove bookmark: " + error);
      }
    );
  }

  // ====================================
  // Return PUBLIC methods and properties
  // ====================================
  var _self =
  {
    Block: Block,
    Unblock: Unblock,

    BookmarkToggleTabs: BookmarkToggleTabs,

    BuildBackgroundProcessProgress: BuildBackgroundProcessProgress,

    ApplyIcons: ApplyIcons,

    ClearTextSelection: ClearTextSelection,

    DisableControlStyling: DisableControlStyling,

    DDListFromArray: DDListFromArray,
    DDListFromCollection: DDListFromCollection,
    DDListFromCsv: DDListFromCsv,
    DDListAdd: DDListAdd,

    GetInputDate: GetInputDate,
    GetInputDateTime: GetInputDateTime,
    HtmlNamedColourToRgb: HtmlNamedColourToRgb,
    HtmlEncode: HtmlEncode,
    OrderElements: OrderElements,
    ScrollToTop: ScrollToTop,
    SelectDocumentManagerFile: SelectDocumentManagerFile,
    SelectFlagColour: SelectFlagColour,
    SelectResource: SelectResource,
    ShowNotification: ShowNotification,

    InitialiseAddressAutoComplete: InitialiseAddressAutoComplete,

    IsSmallMobileBrowser: IsSmallMobileBrowser,

    TableAddRowsFromCollection: TableAddRowsFromCollection,

    ValidateContainer: ValidateContainer,
    Evaluate: Evaluate,

    AccountFinancial: AccountFinancial,
    AccountPaymentDetails: AccountPaymentDetails,
    AccountIncomingPaymentDetails: AccountIncomingPaymentDetails,
    AccountOutgoingPaymentDetails: AccountOutgoingPaymentDetails,
    AddressDetails: AddressDetails,
    BankingDetails: BankingDetails,
    Button: Button,
    ButtonList: ButtonList,
    ButtonStrip: ButtonStrip,
    Calendar: Calendar,
    CheckBox: CheckBox,
    CheckList: CheckList,
    ColourChooserComboBox: ColourChooserComboBox,
    ComboBox: ComboBox,
    CompareItemsGrid: CompareItemsGrid,
    DashboardLayout: DashboardLayout,
    DateBox: DateBox,
    DateCycleComboBox: DateCycleComboBox,
    DateTimeZone: DateTimeZone,
    DBCombo: DBCombo,
    DocumentManagerComboBox: DocumentManagerComboBox,
    DropdownPanel: DropdownPanel,
    ExpiryDate: ExpiryDate,
    FileUpload: FileUpload,
    Form: Form,
    Grid: Grid,
    GroupingList: GroupingList,
    HtmlEditor: HtmlEditor,
    IconComboBox: IconComboBox,
    InformationListComboBox: InformationListComboBox,
    Label: Label,
    Modal: Modal,
    NumberBox: NumberBox,
    ParametersHost: ParametersHost,
    PermissionKeyComboBox: PermissionKeyComboBox,
    PreviewPane: PreviewPane,
    PromptUpdateList: PromptUpdateList,
    RadioButton: RadioButton,
    RadioButtonList: RadioButtonList,
    RangeSlider: RangeSlider,
    Repeater: Repeater,
    TableFilterTextBox: TableFilterTextBox,
    Tabs: Tabs,
    TextBox: TextBox,
    TimeBox: TimeBox,

    Charts: mCharts,
    Forms: mForms,

    ModalOpenCount: ModalOpenCount,
    GetModalById: GetModalById,

    MsgBoxAlert: MsgBoxAlert,
    MsgBoxConfirm: MsgBoxConfirm,
    MsgBoxConfirmList: MsgBoxConfirmList,
    MsgBoxConfirmDelete: MsgBoxConfirmDelete,
    MsgBoxInfo: MsgBoxInfo,
    MsgBoxList: MsgBoxList,

    GetControlRow: GetControlRow,

    DirtyTrackingEnabled: DirtyTrackingEnabled,

    LoadStyle: LoadStyle,
    StyleAsModal: StyleAsModal,

    VisualiseControlChanged: VisualiseControlChanged,

    // Constants
    FIELD_WIDTH_CODE_5: "6em",
    FIELD_WIDTH_CODE_10: "10em",
    FIELD_WIDTH_CODE_15: "12em",
    FIELD_WIDTH_CODE_20: "16em",
    FIELD_WIDTH_CODE_25: "20em",
    FIELD_WIDTH_CODE_25: "20em",

    MANDATORY_CONTROL_BACKGROUNDCOLOUR: "#ffffee",
    MANDATORY_LABEL_COLOUR: "#0070bf",

    // Obsolete (moved to widget)
    Trim: Trim,
    LTrim: LTrim,
    RTrim: RTrim,
    SplitWordsAtCapitals: SplitWordsAtCapitals,
    ArrayFromCsvString: ArrayFromCsvString,

    // Friend
    CreateGuid: CreateGuid,
    GetElement: GetElement,
    ParseJsonDate: Runtime_ParseJsonDate,
  };

  widget.UI = _self;
}(widget);

console.log("  widget.UI (extension)");


/*
#################################################################
 Copyright Intersoft Systems Limited. All Rights Reserved

 jQuery plug-ins
#################################################################
*/
(function ($) {
  $.fn.swapWith = function (that) {
    var $this = this;
    var $that = $(that);

    // create temporary placeholder
    var $temp = $("<div>");

    // 3-step swap
    $this.before($temp);
    $that.before($this);
    $temp.after($that).remove();

    return $this;
  };

  var _seivt = null;

  /* Scroll Element Into View */
  $.fn.ScrollElementIntoView = function (instant, complete, options) {
    // Extend options with defaults
    var ScrollElementIntoView = {
      instant: false,
      duration: null,
      step: null,
      inViewAmount: 0,
      scrollParent: null, // J030277
    };
    var o = $.extend({}, ScrollElementIntoView, options);
    if (instant == true) o.instant = true;

    // Development warnings
    if (o.complete) {
      window.alert("ScrollElementIntoView: o.complete not yet implemented!");
    }

    // Initialise
    var _self = this;

    // Validate
    if (_self.length != 1) {
      console.warn("ScrollElementIntoView is designed only to work on a single element.");
      return;
    }

    // Always add a slight delay in case this has been called in an event such as "keydown" which has in itself scrolled the parent
    if (_seivt) window.clearTimeout(_seivt);
    _seivt = setTimeout(function () {
      window.clearTimeout(_seivt);
      _seivt = null;

      // Get top and height of element to scroll into view
      var y = _self[0].offsetTop;
      var h = _self[0].offsetHeight;

      // Find scrollable parent
      // NOTE: Assume it MUST be a div since this gets around IE issues with tables
      var pe = $(_self[0].parentElement);
      if (o.scrollParent) {
        // J030277
        pe = o.scrollParent;
      }
      else {
        while (pe.length != 0) {
          if (pe[0].tagName == "BODY") {
            break;
          }
          if (pe[0].tagName == "DIV" && pe[0].scrollHeight > $(pe[0]).height()) break;
          pe = $(pe[0].parentElement);
        }
      }

      // Scroll into view (only if necessary)
      if (pe.length == 1) {
        // Get scrollable parent height and scroll position
        var ph = pe.height();
        var psp = pe[0].scrollTop;

        // Scroll
        if (o.instant) pe.stop(true, true);
        if (y - o.inViewAmount < psp) {
          // Scroll in from top
          pe.animate({ scrollTop: y - o.inViewAmount }, o);
        }
        else if (y + h + o.inViewAmount > psp + ph) {
          // Scroll in from bottom
          pe.animate({ scrollTop: y - ph + h }, o);
        }
        else {
          // Complete immediately
          //if (o.complete) o.complete();
        }
      }
      else {
        // Complete immediately
        //if (o.complete) o.complete();
      }
    }, 10);

    return this;
  };
})($);