﻿/*
#################################################################
 Copyright Intersoft Systems Limited. All Rights Reserved

 Widget User Interface utilities v1.41 (5-Aug-2020)

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

 Sub-Objects
 -----------
 * Forms
  * ShowAccountSchedule
  * ShowCompanyLookup
  * ShowHtml
  * ShowHtmlWidgetModal
  * ShowRangeLookupFromStandardRange

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

 General
 -------
 * Block ([message])
 * DisableControlStyling(value)
 * Unblock
 * 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])
 * ScrollToTop(elementId)
 * ValidateContainer(container)
 * LoadStyle(style, [options])
 * Evaluate(elementId, [options])

 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) {
  var mBlockElement = 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 mMinimisedModal = null;
  var mMinimisedModalParent = null;
  var mModalCount = 0;
  var mModalOpenCount = 0;
  var mModalStack = [];

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

  // ===========================================
  // finPOWER Connect Cloud $Runtime substitutes
  // ===========================================
  var Runtime_IsMobileBrowser = false; // Set later
  var Runtime_IsPlatformIOS = false; // Set later
  var Runtime_ParseDate = widget.ParseDate;
  var Runtime_FormatCurrency = widget.FormatCurrency;
  var Runtime_FormatDate = widget.FormatDateInternal;
  var Runtime_ParseJsonDate = function (s) { if (s) { return new Date(s); } else { return null; } };
  var Runtime_FormatNumber = widget.FormatNumber;
  var Runtime_ParseNumber = widget.ParseNumber;
  var 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"; } }
  var 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"; } }
  var 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 ""; } };
  var 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");

        // 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" +
          "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;
  }

  // Other browser specific tweaks
  //   Internet Explorer
  var mBrowserIE = false;
  if (navigator.appVersion.indexOf("MSIE") != -1) {
    mBrowserIE = true;
  }
  else if (navigator.appVersion.indexOf("Trident/") != -1) {
    mBrowserIE = true;
  }
  if (mBrowserIE) $("html").addClass("browser-ie");

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

  // Other support
  if (mBrowserIE) mSupportsStickyHeaders = false;

  // 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();
        }
      }
    });
  });

  // ==============================
  // 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: Handle a jQuery ContextMenu Event
  //
  // NOTE: Requires 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 () {
            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 iconUrl = widget.GetIconUrl(icon);
        if (icon) {
          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: 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");
  }

  // ====================
  // PUBLIC: Block the UI
  // ====================
  function Unblock() {
    if (mBlockElement) {
      // Remove
      mBlockElement.remove();
      mBlockElement = null;
    }
  }

  // =================================
  // 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();
      var streetAddress = "";

      // 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());
        }
      }

      // 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: 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();
      window.setTimeout(function () { $("body").animate({ scrollTop: top }); }, 10);
    }
    else {
      // Scroll document body to the top
      window.setTimeout(function () { $("html,body").animate({ scrollTop: 0 }); }, 10);
    }
  }


  // ==============================================
  // 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, tabs;
    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']", 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.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)
      if (Include && !ctl && !ej.attr("id")) Include = false;

      //if (ctl) window.alert(ctl.TypeName + ", " + Include);

      // 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 (!ej.val()) {
            Ok2 = false;
          }
        }
      }

      // Focus and exit?
      if (!Ok2) {
        Ok = false;
        //if (ctl) window.alert(ctl.TypeName + ", INVALID");
        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
    // NOTE: Typically, you would attach a Calendar to a div element
    if (!e) e = $(document);
    if (typeof e == "string") {
      e = $("#" + e);
    }
    else {
      id = $(e).attr("id");
    }

    // Get elements containing tags within the element and including the element
    var 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
    var s = "";
    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();
          }
          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)

          // Format
          try {
            var 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.text(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 {
          el.html(geval(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'.");
        }
      }
    }
  }



  // ========================
  // PRIVATE: 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 mElementDay;
    var mElementDayName;
    var mElementMonth;
    var mElementResizeSelect;
    var mElementYear;
    var mInitialised = false;
    var mOptions;
    var mValue;
    var mValueOriginal;

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

      readOnly: false,
      autoReadOnly: true,

      onChange: null
    };
    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
        mElementDayName = $("<div class='dayname'></div>");

        var wrapperMonth = $("<div></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>");
        }
        var rightMonth = $("<div class='right month' title='Forward a month'/>");
        wrapperMonth.append(leftMonth);
        wrapperMonth.append(mElementMonth);
        wrapperMonth.append(rightMonth);

        var wrapperDay = $("<div></div>");
        var leftDay = $("<div class='left day' title='Back a day'/>");
        mElementDay = $("<select class='day'></select>");
        for (var i = 1; i < 32; i++) {
          mElementDay.append("<option>" + i + "</option>");
        }
        var rightDay = $("<div class='right day' title='Forward a day'/>");
        wrapperDay.append(leftDay);
        wrapperDay.append(mElementDay);
        wrapperDay.append(rightDay);

        var wrapperYear = $("<div></div>");
        var leftYear = $("<div class='left year' title='Back a year'/>");
        mElementYear = $("<select class='year'></select>");
        for (var i = 0; i < 200; i++) {
          mElementYear.append("<option>" + (1900 + i) + "</option>");
        }
        var rightYear = $("<div class='right year' title='Forward a year'/>");
        wrapperYear.append(leftYear);
        wrapperYear.append(mElementYear);
        wrapperYear.append(rightYear);

        header.append(mElementDayName);
        header.append(wrapperDay);
        header.append(wrapperMonth);
        header.append(wrapperYear);

        // 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>");

          // 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++) {
            mElementCells[x + y * 7] = $("<td></td>");

            // Add
            row.append(mElementCells[x + y * 7]);
          }

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

        // Handle events
        mElementDay.bind("change", function (e) {
          // Set calendar day and refresh
          mCalendarDay = parseInt(mElementDay.val());
          ReformValueFromDropdowns();

          // Focus element
          mElement.focus();
          mElement.select();
        });
        mElementYear.bind("change", function (e) {
          // Set calendar year and refresh
          mCalendarYear = parseInt(mElementYear.val());
          ReformValueFromDropdowns();

          // Focus element
          mElement.focus();
          mElement.select();
        });
        mElementMonth.bind("change", function (e) {
          // Set calendar month and refresh
          mCalendarMonth = mElementMonth[0].selectedIndex;
          ReformValueFromDropdowns();

          // Focus element
          mElement.focus();
          mElement.select();
        });
        leftYear.bind("click", function (e) {
          // Set calendar year and refresh
          mCalendarYear -= 1;
          ReformValueFromDropdowns();
        });
        leftMonth.bind("click", function (e) {
          // Set calendar month and refresh
          mCalendarMonth -= 1;
          if (mCalendarMonth < 0) {
            mCalendarMonth = 11;
            mCalendarYear -= 1;
          }
          ReformValueFromDropdowns();
        });
        leftDay.bind("click", function (e) {
          // Set calendar day and refresh
          mCalendarDay -= 1;
          if (mCalendarDay < 1) mCalendarDay = 31;
          ReformValueFromDropdowns();
        });

        rightMonth.bind("click", function (e) {
          // Set calendar month and refresh
          mCalendarMonth += 1;
          if (mCalendarMonth > 11) {
            mCalendarMonth = 0;
            mCalendarYear += 1;
          }
          ReformValueFromDropdowns();
        });
        rightYear.bind("click", function (e) {
          // Set calendar year and refresh
          mCalendarYear += 1;
          ReformValueFromDropdowns();
        });
        rightDay.bind("click", function (e) {
          // Set calendar day and refresh
          mCalendarDay += 1;
          if (mCalendarDay > 31) mCalendarDay = 1;
          ReformValueFromDropdowns();
        });

        $("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();
            }
          }
        });

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

        var footerPlus1M = $("<button>+Month</button>");
        footerPlus1M.on("click", function () {
          if (!mValue) {
            var d = new Date();
            mValue = new Date(d.getFullYear(), d.getMonth(), d.getDate());
          }
          mValue = new Date(mValue.getFullYear(), mValue.getMonth() + 1, mValue.getDate());
          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();
        });

        mElementFooter.append(footerClear);
        mElementFooter.append(footerToday);
        mElementFooter.append(footerPlus1W);
        mElementFooter.append(footerPlus1M);
        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) 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();
        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) {
          //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()) {
            c.addClass("is-sel");
          }
        }

        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!
      ResizeSelect(mElementDay);
      ResizeSelect(mElementMonth);
      ResizeSelect(mElementYear);

      // 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() {
      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();
      mElement.select();
    }

    // ----------------------------------------------
    // PUBLIC: Goto Value, i.e., ensure it 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: 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();
      }
    }


    // ------------------------------------
    // Return PUBLIC methods and properties
    // ------------------------------------
    var _self =
    {
      Changed: Changed,
      Element: Element,
      Focus: Focus,
      GotoValue: GotoValue,
      ReadOnly: ReadOnly,
      Value: Value
    };
    return _self;
  }



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

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

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

      trAccountSortCode: null,
      txtAccountSortCode: 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,

      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,

      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,
      maxLength: 10,

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

        // Notify
        var e = {};
        if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_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.txtAccountSortCode = TextBox($("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 + 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);
      },
    });
    //    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
        C.trPaymentMethod.show();
        var paymentTypeCategory = "";
        var paymentMethod = null;
        if (C.cboPaymentMethod.ListIndex() != -1) {
          paymentMethod = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()];
          paymentTypeCategory = paymentMethod.PaymentTypeCategory;
        }

        // 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();
            break;

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

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.txtAccountSortCode.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.txtAccountSortCode.AllowBlank(!paymentMethod.HasExportService);
            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(true);
            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();
            }
            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.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.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 "POSCARD":
            // POS Card
            C.trAccountSortCode.hide();
            C.trReference.hide();
            C.trCashRegister.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(true);
            C.cboCardExpiryMonth.AllowBlank(!paymentMethod.HasExportService);
            C.cboCardExpiryYear.AllowBlank(!paymentMethod.HasExportService);
            break;

          case "TOKEN":
            // Token (like Bank Account but without the same validation)
            C.trAccountSortCode.hide();
            C.trCardExpiry.hide();
            C.trCashRegister.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();
            window.alert("Unhandled Payment Type Category '" + paymentTypeCategory + "'.");
        }

        // Other
        if (mRecord) {
        }

        // Read-Only
        C.cboPaymentMethod.ReadOnly(mOptions.readOnly);
        C.txtAccountSortCode.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);

        // Warning
        // NOTE: Also updates Account Number and Sort Code formats if necessary
        if (refetchWarningMessage && mRecord && C.cboPaymentMethod.Text()) {
          mWarningTimer = window.setTimeout(function () {
            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.txtAccountSortCode.Text() && C.txtAccountSortCode.Text() == data.AccountSortCodeOriginal && data.AccountSortCodeFormatted) {
                      C.txtAccountSortCode.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) {
      // Extend options with defaults
      var InitialiseDefaults = {
        applyDefaultPaymentMethod: false,
        applyDefaultCashRegister: false,

        branchId: "",

        defaultValuesOnPaymentMethodChange: false,
      };
      options = $.extend({}, InitialiseDefaults, options);

      // Initialise
      mAccountId = accountId;
      mInitialised = false;
      mDefaultValuesOnPaymentMethodChange = options.defaultValuesOnPaymentMethodChange;
      mWarningMessage = "";
      if (mWarningTimer) {
        window.clearTimeout(mWarningTimer);
        mWarningTimer = null;
      }
      UpdateElement(false);

      // Reference Tags
      var tags = [];
      if (mAccountId !== undefined && !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
      if (mOptions.showCashRegister) {
        C.cboCashRegister.RefreshFromStandardRange("CashRegisters");
      }
      else {
        C.cboCashRegister.VisibleRow(false);
      }

      // 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
            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);
            }

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

            // Load smart?
            if (options.defaultValuesOnPaymentMethodChange && data.DefaultPaymentMethodId) {
              if (mOptions.paymentEntry) {
                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);
        }
      );
    }

    // -------------
    // 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: AccountSortCode property
    // --------------------------------
    function AccountSortCode(value) {
      if (value === undefined) {
        // Get
        return C.txtAccountSortCode.Text();
      }
      else {
        // Set
        if (value != C.txtAccountSortCode.Text()) {
          C.txtAccountSortCode.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) {
      // Parse
      if (json) {
        try {
          var o = JSON.parse(json);

          // Update fields
          C.cboPaymentMethod.Text(o.PaymentMethodId);
          C.txtAccountSortCode.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);

          // 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;
      }

      // 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) {
              FromBankingDetailsJson(data.BankingDetailsJson);
            }
          }
          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 = {};

      o.PaymentMethodId = C.cboPaymentMethod.Text();
      o.AccountSortCode = C.txtAccountSortCode.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();

      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];

            switch (mPaymentTypeCategoryFilter.toUpperCase()) {
              case "":
                // All
                mPaymentMethodsFiltered.push(item);
                break;

              case "DIRECTCREDIT":
                // Special, pseudo-category
                if (item.IsDirectCredit) {
                  mPaymentMethodsFiltered.push(item);
                }
                break;

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

          }
        }

        // 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();
    }


    // ------------------------------------
    // 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,

      PaymentMethodId: PaymentMethodId,
      PaymentMethodAllowBlank: PaymentMethodAllowBlank,
      PaymentTypeCategoryFilter: PaymentTypeCategoryFilter,
      AccountSortCode: AccountSortCode,
      AccountNumber: AccountNumber,
      AccountName: AccountName,
      CardExpiryMonthIndex: CardExpiryMonthIndex,
      CardExpiryYear: CardExpiryYear,
      CardSecurityCode: CardSecurityCode,
      CashRegisterId: CashRegisterId,
      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 mOptions;
    var mPaymentTypeCategoryFilter = "";
    var mPaymentMethods;
    var mPaymentMethodsFiltered;
    var mRecord;
    var mTransactionDate = null;
    var mWarningMessage = "";
    var mWarningTimer;

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

      trAccountSortCode: null,
      txtAccountSortCode: 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,

      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,

      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,
      maxLength: 10,

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

        // Notify
        var e = {};
        if (mOptions.onPaymentMethodChange) mOptions.onPaymentMethodChange(_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.txtAccountSortCode = TextBox($("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 + 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);
      },
    });
    //    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
        C.trPaymentMethod.show();
        var paymentTypeCategory = "";
        var paymentMethod = null;
        if (C.cboPaymentMethod.ListIndex() != -1) {
          paymentMethod = mPaymentMethodsFiltered[C.cboPaymentMethod.ListIndex()];
          paymentTypeCategory = paymentMethod.PaymentTypeCategory;
        }

        // 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();
            break;

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

            if (mRecord && mRecord.BankSortCodeCaption) {
              C.txtAccountSortCode.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.txtAccountSortCode.AllowBlank(!paymentMethod.HasExportService);
            C.txtAccountNumber.AllowBlank(!paymentMethod.HasExportService);
            C.txtName.AllowBlank(true);
            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();
            }
            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.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.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 "POSCARD":
            // POS Card
            C.trAccountSortCode.hide();
            C.trReference.hide();
            C.trCashRegister.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(true);
            C.cboCardExpiryMonth.AllowBlank(!paymentMethod.HasExportService);
            C.cboCardExpiryYear.AllowBlank(!paymentMethod.HasExportService);
            break;

          case "TOKEN":
            // Token (like Bank Account but without the same validation)
            C.trAccountSortCode.hide();
            C.trCardExpiry.hide();
            C.trCashRegister.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();
            window.alert("Unhandled Payment Type Category '" + paymentTypeCategory + "'.");
        }

        // Other
        if (mRecord) {
        }

        // Read-Only
        C.cboPaymentMethod.ReadOnly(mOptions.readOnly);
        C.txtAccountSortCode.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);

        // Warning
        // NOTE: Also updates Account Number and Sort Code formats if necessary
        if (refetchWarningMessage && mRecord && C.cboPaymentMethod.Text()) {
          mWarningTimer = window.setTimeout(function () {
            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.txtAccountSortCode.Text() && C.txtAccountSortCode.Text() == data.AccountSortCodeOriginal && data.AccountSortCodeFormatted) {
                      C.txtAccountSortCode.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 {
        if (mWarningMessage) {
          C.divWarning.html(HtmlEncode(mWarningMessage));
        }
        else {
          C.divWarning.css("color", "darkred");
          C.divWarning.text("Initialising, please wait...");
        }
        C.trWarning.show();
      }

      // Reference Tags
      var tags = [];
      if (mAccountId !== undefined && !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);
    }

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

        branchId: "",

        defaultValuesOnPaymentMethodChange: false,
      };
      options = $.extend({}, InitialiseDefaults, options);

      // Initialise
      mAccountId = accountId;
      mInitialised = false;
      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
          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);
          }

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

          // Load smart?
          if (options.defaultValuesOnPaymentMethodChange && data.DefaultPaymentMethodId) {
            if (mOptions.paymentEntry) {
              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 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: AccountSortCode property
    // --------------------------------
    function AccountSortCode(value) {
      if (value === undefined) {
        // Get
        return C.txtAccountSortCode.Text();
      }
      else {
        // Set
        if (value != C.txtAccountSortCode.Text()) {
          C.txtAccountSortCode.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) {
      // Parse
      if (json) {
        try {
          var o = JSON.parse(json);

          // Update fields
          C.cboPaymentMethod.Text(o.PaymentMethodId);
          C.txtAccountSortCode.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);

          // 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;
      }

      // 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()) {
            if (data.BankingDetailsJson) {
              FromBankingDetailsJson(data.BankingDetailsJson);
            }
          }
          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 = {};

      o.PaymentMethodId = C.cboPaymentMethod.Text();
      o.AccountSortCode = C.txtAccountSortCode.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();

      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];

            switch (mPaymentTypeCategoryFilter.toUpperCase()) {
              case "":
                // All
                mPaymentMethodsFiltered.push(item);
                break;

              case "DIRECTCREDIT":
                // Special, pseudo-category
                if (item.IsDirectCredit) {
                  mPaymentMethodsFiltered.push(item);
                }
                break;

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

          }
        }

        // 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();
    }


    // ------------------------------------
    // 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,

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

      ShowCashRegister: ShowCashRegister,
      ShowChequeNumber: ShowChequeNumber,

      TransactionDate: TransactionDate,

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

      WidthResizeFromParent: WidthResizeFromParent,
    };
    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 C = {
      trDeliveryType: null,
      cboDeliveryType: null,

      trPropertyName: null,
      txtPropertyName: null,

      trStreetAddress: null,
      txtStreetAddress: 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,

      showCity: true,
      showCountry: true,
      showDeliveryType: false,
      showInstructions: false,
      showPostalId: false,
      showPropertyName: 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);
    //    Delivery Type
    C.trDeliveryType = $("<tr style='display:none'><th><label for='" + cid + "'>Delivery Type:</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:&nbsp;</label></th><td><input id='" + cid + "'/></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:</label></th><td><input id='" + cid + "'/></td>");
    mElement.append(C.trStreetAddress);
    C.txtStreetAddress = TextBox($("input", C.trStreetAddress), {
      maxLength: 130,

      onChange: Address_Changed,
    });
    //    Suburb
    cid += "X";
    C.trSuburb = $("<tr><th><label for='" + cid + "'>Suburb:</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:</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:</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:</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:</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:</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();
      }
      C.cboDeliveryType.VisibleRow(mOptions.showDeliveryType);
      C.txtPropertyName.VisibleRow(mOptions.showPropertyName);
      C.txtCity.VisibleRow(mOptions.showCity);
      C.cboCountry.VisibleRow(mOptions.showCountry);
      C.txtPostalId.VisibleRow(mOptions.showPostalId);

      // Read-Only
      C.cboDeliveryType.ReadOnly(mOptions.readOnly);
      C.txtPropertyName.ReadOnly(mOptions.readOnly);
      C.txtStreetAddress.ReadOnly(mOptions.readOnly);
      C.txtSuburb.ReadOnly(mOptions.readOnly);
      C.txtCity.ReadOnly(mOptions.readOnly);
      C.cboState.ReadOnly(mOptions.readOnly);
      C.txtPostcode.ReadOnly(mOptions.readOnly);
      C.cboCountry.ReadOnly(mOptions.readOnly);
      C.txtPostalId.ReadOnly(mOptions.readOnly);

      // 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
      if (C.cboCountry.Text() == mRecordCountryInfo.Country) C.cboState.ListFromCsvString(mRecordCountryInfo.States);
      // Terminology
      C.cboState.Caption(mRecordCountryInfo.TerminologyState + ":");
      C.txtPostcode.Caption(mRecordCountryInfo.TerminologyPostcode + ":");
      C.txtSuburb.VisibleRow(mRecordCountryInfo.SupportsSuburb);
      C.cboState.VisibleRow(mRecordCountryInfo.SupportsState);
      C.txtPostcode.VisibleRow(mRecordCountryInfo.SupportsPostcode);
      // Other
      if (mRecordCountryInfo.PostalValidationAvailable && !mOptions.readOnly) {
        C.cmdCheckPostalId.show();
      }
      else {
        C.cmdCheckPostalId.hide();
      }

      // Delivery Type
      if (IsDeliveryTypeBagOrBox()) {
        C.txtStreetAddress.Caption("Details:");
        C.txtPropertyName.VisibleRow(false);
      }
      else {
        C.txtStreetAddress.Caption("Street:");
      }
    }

    // -------------------
    // PRIVATE: Initialise
    // -------------------
    function Initialise() {
      // Initialise
      mWarningMessage = "";

      // Get Initialisation details
      widget._SystemGetString("AddressDetails_Initialise", {},
        function (data) {
          if (data) {
            // Parse
            data = JSON.parse(data);
            mRecord = data;

            // Lists
            C.cboCountry.ListFromCsvString(mRecord.CountriesList);
            cboCountry_Change();

            // Other
            C.cboCountry.BlankTip(mRecord.DefaultCountry);
          }
        },

        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);
            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;
        }
      }
    }

    // -------------------------
    // 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() && !C.txtStreetAddress.Text()) {
        if (userInvoked) {
          widget.UI.MsgBoxAlert("You must enter either a Delivery/ Postal Id or Street Address/ Details.", {}, 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;

        // Build update list
        var list = [];
        if (mOptions.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 (mOptions.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 (mOptions.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 (mOptions.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("Delivery/ Postal Id matches the Address.");
            }
            else {
              widget.UI.MsgBoxAlert("No Delivery/ Postal Id was found for this Address.");
            }
          }
        }
        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: C.cboCountry.Text() },
          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
      C.cboDeliveryType.ListFromCsvString(mRecordCountryInfo.DeliveryTypes);

      // 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 {
        // Set
        mOptions.showCity = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------
    // PUBLIC: Show Country property
    // -----------------------------
    function ShowCountry(value) {
      if (value === undefined) {
        // Get
        return mOptions.showCountry;
      }
      else {
        // Set
        mOptions.showCountry = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------------
    // PUBLIC: Show Delivery Type property
    // -----------------------------------
    function ShowDeliveryType(value) {
      if (value === undefined) {
        // Get
        return mOptions.showDeliveryType;
      }
      else {
        // Set
        mOptions.showDeliveryType = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -------------------------------
    // PUBLIC: Show Postal Id property
    // -------------------------------
    function ShowPostalId(value) {
      if (value === undefined) {
        // Get
        return mOptions.showPostalId;
      }
      else {
        // Set
        mOptions.showPostalId = value;

        // Refresh
        UpdateElement(false);
      }
    }

    // -----------------------------------
    // PUBLIC: Show Property Name property
    // -----------------------------------
    function ShowPropertyName(value) {
      if (value === undefined) {
        // Get
        return mOptions.showPropertyName;
      }
      else {
        // 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);

        // Update fields
        C.cboDeliveryType.Text(o.DeliveryTypeText);
        C.txtPropertyName.Text(o.PropertyName);
        C.txtStreetAddress.Text(o.StreetAddress);
        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 = {};

      if (mOptions.showDeliveryType) o.DeliveryTypeText = C.cboDeliveryType.Text();
      if (mOptions.showPropertyName) o.PropertyName = C.txtPropertyName.Text();
      o.StreetAddress = C.txtStreetAddress.Text();
      o.Suburb = C.txtSuburb.Text();
      if (mOptions.showCity) o.City = C.txtCity.Text();
      o.State = C.cboState.Text();
      o.Postcode = C.txtPostcode.Text();
      if (mOptions.showCountry) o.Country = C.cboCountry.Text();
      if (mOptions.showPostalId) o.PostalId = C.txtPostalId.Text();

      return JSON.stringify(o);
    }

    // --------------------------
    // PUBLIC: Resize from Parent
    // --------------------------
    function 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,
      ShowPostalId: ShowPostalId,
      ShowPropertyName: ShowPropertyName,

      AdvancedCity: AdvancedCity,
      AdvancedPostalId: AdvancedPostalId,
      AutoValidateAddress: AutoValidateAddress,

      IsDeliveryTypeBagOrBox: IsDeliveryTypeBagOrBox,

      WidthResizeFromParent: WidthResizeFromParent,
    };
    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",

      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();

      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 index='" + i + "'></li>");

          // 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 == i) {
            li.addClass("selected");
          }

          // Get button text
          item._captionText = li.text();

          ul.append(li);
        }
      }

      mElement.append(ul);

      // Read-only
      if (mOptions.readOnly) {
        mElement.addClass("is-readonly");
      }
      else {
        mElement.removeClass("is-readonly");
      }

      // 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";
      }
      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!

          // Read-Only
          //TODO:

          // Get button text
          item._captionText = li.text();

          ul.append(li);
        }
      }

      mElement.append(ul);

      // Read-only
      if (mOptions.readOnly) {
        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 + "'>" + 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: "inline-block" });
          mValidationElement.addClass("is-block");
        }
        else {
          mValidationElement.css({ display: "none" });
          mValidationElement.removeClass("is-block");
        }
      }

      // 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;
    }

    // ----------------------------------
    // 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";
      }
      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();
      window.setTimeout(function () {
        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: 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";
      }
      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
      window.setTimeout(function () {
        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,
      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 (!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 = new window.parent.$UI.ComboBox(e, options);
      return c;
    }


    var mButtonElement;
    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,
      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'/>");
    }
    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("");
            }
          }
        }
      });

      mElement.bind("keydown", function (e) {
        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 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.limitToList) {
              // Value will be cleared later
            }
            else {
              moveX = -1;
            }
            break;

          case 8: // Backspace
            moveX = -1;
            break;

          default:
            if (e.keyCode < 48) return;
            break;
        }

        // 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");
      }

      // Never show button?
      if (!mOptions.allowDropdown) {
        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();
      }
    }

    // ---------------
    // 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);
          //}
        }
        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
        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();
      }
    }

    // ------------------------
    // 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();
      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: 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: 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";
      }
      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,
      AutoReadOnly: AutoReadOnly,
      BlankTip: BlankTip,
      Caption: Caption,
      Changed: Changed,
      DropdownHide: DropdownHide,
      DropdownShow: DropdownShow,
      DropdownShowing: DropdownShowing,
      Element: Element,
      Focus: Focus,
      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; },
    };
    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);
                  window.setTimeout(function () { 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 (!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 = {
      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,

      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'/>");
    }
    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'/>");
    }
    if (mOptions.usePicker) {
      mButtonElement.addClass("is-picker");
    }
    mWrapperElement.append(mButtonElement);

    // Time portion
    if (mOptions.allowTime) {
      mElementTime = $("<input class='is-timebox' style='width:6em;margin-left:4px;text-align:right' 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");
      }

      // 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");
        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: "inline-block" });
        }
        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, {
          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
      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: 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();
      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: 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") {
          // 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());
        }

        // 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("ComboBox.VisibleRow: no parent row element found.")
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return mElementRow.css("visibility").toUpperCase() == "HIDDEN";
      }
      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.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,
      Caption: Caption,
      Changed: Changed,
      DropdownHide: DropdownHide,
      DropdownShow: DropdownShow,
      Element: Element,
      Focus: Focus,
      MaxValue: MaxValue,
      MinValue: MinValue,
      ReadOnly: ReadOnly,
      Value: Value,
      ValueAsISOString: ValueAsISOString,
      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: Date Cycle Combo Box object
  // ===================================
  function DateCycleComboBox(e, options) {

    // Use finPOWER Connect Cloud DateCycleComboBox (to respect picker panel etc)
    if (!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 = new 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 (!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 = new window.parent.$UI.DBCombo(e, options);
      return c;
    }


    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 mFilterText = "";
    var mFilteredOutCount = 0;
    var mInternalHoldChangeEvent = 0;
    var mIsSelectElement;
    var mLabelElement;
    var mList = [];
    var mListDescription = [];
    var mListDirty = false;
    var mListElement;
    var mOptions;
    var mTextOriginal = "";
    var mWrapperElement;

    var mQuickSearchResults = null;
    var mQuickSearchResultsGrid = 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

      width: "auto",

      onChange: 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; align-items:center; padding:0; margin:0; position:relative;' controlType='dbcombo'/>");
    mWrapperElement = $(mElement.parent());

    // Dropdown button
    mButtonElement = $("<button type='button' tabindex='-1' class='is-combobox-button' style='position:relative;left:1px;top:0'/>");
    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;
    }

    // Dropdown panel
    if (mOptions.showColumnHeadings) {
      mDropdownPanel = new DropdownPanel(mWrapperElement, { attachedControl: _self });
    }
    else {
      // Not showing column headings so don't size less than parent control
      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();

    // Handle events
    mElement.bind("keydown", function (e) {
      switch (e.keyCode) {
        //case 13: // Enter
        //  if (mDropdownPanel.Visible()) DropdownHide(true);
        //  break;

        case 27: // Escape
          if (mDropdownPanel.Visible()) DropdownHide(false);
          break;

        case 38: // Cursor Up
          if (mDropdownPanel.Visible()) {
            ListIndexChange(-1);
            if (mDropdownPanel.Visible()) UpdateListSelectedItem();
          }
          break;

        case 40: // Cursor Down
          if (mDropdownPanel.Visible()) {
            ListIndexChange(1);
            UpdateListSelectedItem();
          }
          else if (!mOptions.readOnly) {
            DropdownShow();
          }
          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.limitToList) {
            // Value will be cleared later
          }
          else {
            moveX = -1;
          }
          break;

        case 8: // Backspace
          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();
      }
    });

    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();
        }
      }

      // 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();
      }
    }

    // ----------------------
    // 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;
                  }
                  window.setTimeout(function () {
                    // Get description
                    var params = { standardRangeName: mSpecialStandardRangeName, id: id };

                    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
                  mDescriptionElement.text("!");
                  mDescriptionElement.addClass("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) {
        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);
        window.setInterval(function () {
          var e = $("input", mFilterBoxElement);
          if (e.val() != mFilterText) {
            ApplyFilter(e.val());
          }
        }, 200);
      }

      // 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);
          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);
          if (mOptions.usePicker) {
            UpdateListSelectedItem();
            SharedPickerPanel().Hide(true);
          }
        }
      });

      // Append
      if (!mOptions.usePicker) mDropdownPanel.Append(mListElement);
    }

    function UpdateList_Collection() {
      var displayColumns;
      var options;

      // Split display columns
      displayColumns = mDataSourceDisplayColumns.split(",");

      // 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);
          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 input = $("<input type='text' style='position:absolute !important; top:0; left:0; width:100%;border:1px solid transparent !important; border-bottom:1px solid rgba(0,0,0,0.2) !important'/>")
      var btn = $("<button class='is-button dbcombo-search' style='min-width:0; width:22px; height:22px; margin:0; position:absolute; right:2px; top:0;'/>");
      var div = $("<div style='position:absolute; top:22px;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;

        default:
          input.attr("placeholder", "e.g. code, name");
          break;
      }

      mListElement.append(input);
      mListElement.append(btn);
      mListElement.append(div);

      mQuickSearchResultsGrid = new Grid(div, {
        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()); },
      });

      // 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() {
      if (mQuickSearchResults && mQuickSearchResults.Results && mQuickSearchResultsGrid.ActiveDataRowIndex() != -1) {
        var item = mQuickSearchResults.Results[mQuickSearchResultsGrid.ActiveDataRowIndex()];

        if (item) mElement.val(item.Id);
        UpdateDescription();
        NotifyChange(true);
      }
    }
    function UpdateList_CollectionSpecialStandardRange_RowDrilldown(e) {
      mDropdownPanel.Hide();
      mElement.focus();
    }

    // ---------------------
    // PRIVATE: Apply filter
    // ---------------------
    function ApplyFilter(filterText) {
      mFilterText = filterText;

      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");
            }
          }

          // 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
        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 TextBox
        if (mSpecialStandardRangeName) {
          $("input", mListElement).focus();
        }
        else {
          mElement.focus();
          mElement.select();
        }
      }

      // Highlight selected item in list
      UpdateListSelectedItem();

      // Showing
      mDropdownShowing = true;
    }

    // ----------------------------
    // 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) {
      // 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("");
      }

      // Notify
      var e = { ChangeHandled: false, TextOriginal: mTextOriginal, ChangedFromPopup: changedFromPopup };
      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();
      mElement.select();
    }

    // ------------------------------------------------------------------------------------
    // PUBLIC: Get the Description (since this is fetched asynchronously, use with caution)
    // ------------------------------------------------------------------------------------
    function GetDescription() {
      if (!mDescriptionElement) return "";

      // Initialise
      return mDescriptionElement.text();
    }

    // ----------------
    // 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 === 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") {
            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;
          }
        }

        // 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) {
            widget.RegisterError("widget_ui.DBCombo: Failed to retrieve Standard Range: " + data);

            // Failed to get list. Not much we can do!
            if (callback) callback();
          }
        );
      }
    }

    // ----------------------------------------------------------------------------------------------
    // 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");
        //mDescriptionElement.css("height", "22px");
        //mDescriptionElement.css("line-height", "22px");
      }
      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";
      }
      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,
      Text: Text,
      Visible: Visible,
      VisibleRow: VisibleRow,
      WidthResizeFromParent: WidthResizeFromParent,

      /* Friend (internal use only) */
      WrapperElement: function () { return mWrapperElement; },
    };
    return _self;
  }



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

    var mAttachedElement;
    var mAttachedControl;
    var mDropdownElement;
    var mOptions;
    var mVisible = false;

    var mDropdownDocument;
    var mDropdownWindow;

    // 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?
          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 });
          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();
      window.setTimeout(function () { 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().DropdownHide) {
                      // Let the attached control gracefully hide dropdown
                      dd.AttachedControl().DropdownHide();
                    }
                    else {
                      // Hide
                      dd.Hide();
                    }
                  }
                }
              }
            }
            break;
        }
      });
    }
    mDropdownWindow.__ISDropdownHandler.push(_self);


    return _self;
  }



  // ===================
  // 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 (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' 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);

      // 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>");
      body.append(links);
      for (var i = 0; i < actions.length; i++) {
        // Initialise
        action = actions[i];
        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) {
          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);

              // Apply theme information (since Widgets not nothing about finPOWER Connect Cloud theming)
              e.css("color", mThemeContrastColour);
            }

            // Action
            e = $("<li class='action'></li>");
            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);
              /* NOTE: Smaller than finCC since widgets are shown in an iframe */
              if (window.innerWidth >= 640) {
                // Tiled
                iconUrl = widget.GetIconUrl(action.icon, 32);
              }
              else {
                // List
                iconUrl = widget.GetIconUrl(action.icon, 16);
              }
              ei.attr("src", iconUrl);
            }
            ec = $("<span></span>");
            ec.text(action.caption);
            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 (false) {
        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();
    }

    // -----------------------------------
    // PRIVATE: Style up a file-type Input
    //
    // Version Date: 29-Oct-2018
    // -----------------------------------
    function InputFileInitialise(el) {
      // Supported?
      if (!window.FileReader) return;

      // 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 "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: 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;'>XXXX</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 mButtonsElement;
    var mCaptionElement;
    var mCaptionContentElement;
    var mCaptionCloseElement;
    var mCaption = "";
    var mColumns = [];
    var mColumnsDirty = true;
    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 mHiddenRowsVisible = false;
    var mInitialised = false;
    var mInvalidMessageElement;
    var mMenuPopup;
    var mMergedHeadersElement;
    var mNewRowCount = 0;
    var mOptions;
    var mSelectedRowElement;
    var mSorted = false;
    var mStickyFooterElement;
    var mStickyHeaderElement;
    var mStickyHeaderWrapperElement;
    var mStickyHeaderWrapperElement_OldTop = 0;
    var mTableWrapper;
    var mTemplateRow;
    var mVirtualClass;
    var mVirtualData;
    var mWrapperElement;

    mActions = new ActionsCollection();

    // Grid column defaults
    GridColumnDefaults = {
      key: "",

      align: "",
      allowDrilldown: false,
      blankIfZero: false,
      caption: null,
      drilldownGlyph: null,
      readOnly: false,
      selectable: false,
      sortable: false,
      style: "",
      summary: "",
      tooltipText: "",
      type: "string",
      visible: true,
      width: "",

      thElement: null,
      original: false,

      elementCreatedIndex: -1
    };

    // Extend options with defaults
    GridDefaults = {
      cssClass: "is-grid",

      groupByColumns: "",
      groupByDesc: false,         // Only applied if true OR if sorted
      groupingsCollapsed: false,  // Collapse groupings by default (upon performing a VirtualDataRefresh)

      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,

      sortByColumn: "",
      sortByDesc: false,

      showContextMenu: true,
      showHiddenRowsPopup: true,

      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);

    // 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 {
              window.alert("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 "Integer":
                // Clear number
                // NOTE: For some reason the number box swallows the delete key!
                PerformBeforeCellUpdate(mActiveDataRowIndex, mActiveColumnKey, null, true);
                break;

              default:
                EditorEnterEditMode();
                window.setTimeout(function () { 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;
              }
            }
          }

          //window.alert(e.keyCode + " - " + e.which);
          break;
      }
    });

    // Initialise
    if (mColumns.length == 0) {
      // Do nothing if no columns since the Refresh method should be called after adding columns etc
    }
    else {
      UpdateElement(true);
    }


    // ------------------------------------------------------
    // 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 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 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: 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) {
      if (!matchOnCaption) matchOnCaption = false; else matchOnCaption = true;

      // Hide all columns
      for (var i = 0; i < mColumns.length; i++) {
        mColumns[i].visible = false;
      }

      // 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) {
      var CountHidden = 0;
      var LastGroup = null;

      // Initialise (i.e., create/ initialise elements)?
      if (initialise || !mInitialised) {
        // Flag
        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");
        }

        // Main Element
        mElement.addClass(mOptions.cssClass);
        if (mOptions.style) {
          mElement.addClass(mOptions.style);

          switch (mOptions.style.toUpperCase()) {
            case "REPORT":
              break;
            default:
              console.warn("widget.UI.Grid: Invalid grid style '" + mOptions.style + "'. Supported styles are: 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", ShowHiddenRows);
        }

        // 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);
              }
            });
          }
        }

        // 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);
              }

              //// Delay exiting edit mode slightly so that popups such as dropdown lists get time to fire their change events etc
              //if (mDocumentMouseDown) {
              //  // Ignore
              //  window.alert("document mouse down");
              //}
              //else {
              //  window.setTimeout(function () {
              //    if (!mEditingDbComboSpecial || (mEditingDbComboSpecial && !mEditElement.dbcombo.DropdownShowing())) {
              //      console.log("editing edit mode due to delayed focusout");
              //      EditorExitEditMode(false);
              //    }
              //  }, 100);
              //}
            }
          });

          // 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
          ec = $("<input/>");
          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;
            }
          });

          // DBCombo
          ec = $("<input/>");
          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) {
                EditorExitEditMode(false);
              }
            }
          });
          mEditElementControls.dbcombo.Element().css({ "background-color": "white" });
          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++) {
          var col = mColumns[i];

          // Editable?
          if (col.allowEdit) mEditable = 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
            }
            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);
            }
            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, "");

          // 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:
              window.alert("widget.UI.Grid: Invalid column summary type '" + c.summary + "'. Supported types are: count, sum, $sum, custom");
              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;

        // Sort Virtual Data?
        if (mOptions.sortByColumn || (mOptions.groupByColumns && mOptions.groupByDesc)) {
          if (mOptions.groupByColumns) {
            var g = mOptions.groupByColumns;
            if (mOptions.groupByDesc) 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 = 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);
                groupTd.text(group); // TODO: Raise an event to get the group header text

                // Collapse/ expand group button
                var ghb = $("<div group-index='" + groupIndex + "'></div>");
                if (mOptions.groupingsCollapsed) ghb.addClass("collapsed");
                groupTd.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 (dataRow.hidden) 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);

            // 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) CountHidden += 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
      if (mOptions.showContextMenu) {
        HandleContextMenuEvent($("*", 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 (CountHidden != 0 && mOptions.showHiddenRowsPopup) {
        if (CountHidden == 1) {
          mCaption = "1 row is hidden";
        }
        else {
          mCaption = CountHidden + " rows are hidden";
        }
        mCaption += ". Click to show.";
        mCaptionContentElement.text(mCaption);
      }
      else {
        mCaption = "";
      }

      // Show/ hide caption
      if (mCaption) mCaptionElement.show(); else mCaptionElement.hide();

      // Refresh buttons
      RefreshButtons();

      // Update Editor
      EditorUpdate(false, true);

      // Finalise
      mColumnsDirty = false;
    }

    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" });
      }

      // 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 "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);
            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 "INTEGER":
          editorInfo.type = "numberbox";
          editorInfo.decimals = 0;
          break;

        case "STRING":
        case "CODE":
          if (c.listCsv) {
            // CSV List
            editorInfo.type = "listbox";
            editorInfo.canLimitToList = true;
            editorInfo.limitToList = c.limitToList ? true : false;
            editorInfo.listCsv = c.listCsv;
            editorInfo.collection = null;
            editorInfo.standardRange = null;
          }
          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;
          break;

        default:
          window.alert("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 "DATEBOX":
            newValue = Runtime_ParseDate(mEditElementControls.textbox.Text(), mEditorInfo.historic, true);
            break;

          case "DBCOMBO":
            newValue = mEditElementControls.dbcombo.Text();

            // Limit to list?
            if (mEditorInfo.canLimitToList) {
              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":
            newValue = mEditElementControls.numberbox.Value();
            break;

          case "TEXTBOX":
            newValue = mEditElementControls.textbox.Text();
            break;

          default:
            window.alert("No editor handled for exiting edit mode for editorInfo type '" + mEditorInfo.type + "'.");
            newValue = undefined;
        }

        // Commit changes
        if (newValue === undefined) {
          // Cannot update
          window.alert("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.dbcombo.Visible(false);
          mEditElementControls.listbox.Visible(false);
          mEditElementControls.numberbox.Visible(false);
          mEditElementControls.textbox.Visible(false);

          switch (mEditorInfo.type.toUpperCase()) {
            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({ height: mEditElement.innerHeight() + "px", backgroundColor: "white !important", border: "none", borderRadius: 0 });
              if (!mEditorInfo.valueOriginal) mEditorInfo.valueOriginal = ""; // Undefined, null etc
              mEditElementControls.dbcombo.Text(mEditorInfo.valueOriginal);
              mEditElementControls.dbcombo.LimitToList(mEditorInfo.limitToList);
              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.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 {
                window.setTimeout(function () {
                  // Slight delay to let things catch up
                  mEditElementControls.dbcombo.DropdownShow();
                }, 10);
              }
              break;

            case "LISTBOX":
              mEditElementControls.listbox.Visible(true);
              mEditElementControls.listbox.Element().css({ height: mEditElement.innerHeight() + "px", backgroundColor: "white !important", border: "none", borderRadius: 0 });
              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.Focus();
              window.setTimeout(function () {
                // 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:
              window.alert("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");
        if (st != mStickyHeaderWrapperElement_OldTop) {
          // Scrolled vertically
          // NOTE: IE and Edge jitter so hide header and then scroll down for these browsers
          if (mBrowserIE) {
            mStickyHeaderWrapperElement_OldTop = st;
            mStickyHeaderElement.hide();

            window.setTimeout(function () {
              mStickyHeaderElement.fadeIn("fast");
            }, 500);
          }

          //console.warn("scrolled vertically");
        }

        // 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 "INTEGER":
                    s = widget.FormatCurrency(total, c.summary.substr(0, 1) == "$");
                    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 = a.cells[o].sortValue || a.cells[o].value;
            var 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) {
      // 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 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>");

        // 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");

              // 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>");
        }

        // Template row?
        if (i == -1) {
          rs.append("<span class='templaterow'></span>");
        }

        // Insert
        row.append(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) {
            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");
                      ActiveDataRowIndex(index);
                      ActiveColumnIndex(colIndex);
                      PerformBeforeCellUpdate(index, 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 "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 "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) {
                  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 {
                  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");

            // Callback to get cell value?
            if (cellData.value && cellData.value.eventId) {
              // Clear
              td.text("");

              // Callback
              (function (td, eventId, params) {
                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
          row.append(td);
        }
      }

      // 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) row.addClass("hidden");
      if (dataRow.inactive) row.addClass("inactive");
      if (dataRow.readOnly) row.addClass("readonly");
      if (dataRow.strike) row.addClass("strike");
    }

    // -------------------------
    // Format a TH or TD element
    // -------------------------
    function FormatColumnCell(col, cell, type) {
      // 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 "INTEGER":
            cell.css("text-align", "right");
            break;

          case "DATETIME":
            cell.css({ "text-align": "right", "white-space": "nowrap" });
            break;
        }
      }

      // 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 "INTEGER":
            cell.css("width", "4em");
            break;
        }
      }

      // So hyperlinks can be styled accordingly
      if (col.type.toUpperCase() == "CODE") {
        cell.attr("data-type", "code");
      }

      // 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 = { 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) {
      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 {
            var e = { row: { listIndex: ActiveDataRowListIndex() } };
            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].listIndex == value) {
            ActiveDataRowIndex(i, holdEvents);
            break;
          }
        }
      }
    }

    // ------------------------------------------
    // PUBLIC: Activate First non-hidden 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 (!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 (mVirtualClass) {
        var index = -1;

        for (var i = mVirtualClass.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;
    }

    // -------------------------------------
    // 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: "",

          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
      };

      // Add auto-binding ability
      row.AutoBind = function (item) { RowAutoBind(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];
          }
        }
      }
    }

    // --------------------------------
    // 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) {
          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 };
      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 (and hide the caption)
    // -----------------------------------------------
    function ShowHiddenRows() {
      $("tr.hidden", mElement).removeClass("hidden");
      mCaptionElement.slideUp("fast");

      ActiveDataRowScrollIntoView();

      mHiddenRowsVisible = true;

      // Stripe rows
      //if (mOptions.stripe) StripeRows();

      // Resize Sticky Header
      if (mOptions.stickyHeader) ResizeStickyHeader();
    }

    // ----------------------------
    // 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) {
        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 };

            // Add to virtual data
            mVirtualData.push(row);

            // Call
            mOptions.onInitialiseRow(e);
          }
        }
      }
      catch (ex) {
        window.alert("widget.UI.Grid.VirtualDataRefresh: " + ex.message);
      }

      // Refresh layout
      //Refresh(!mInitialised);
      if (!holdRebuild) Refresh(true);

      // Restore Active Data Row Index
      if (retainActiveDataRowIndex) {
        ActiveDataRowIndex(-2);
        ActiveDataRowIndex(oldActiveDataRowIndex);
      }
      else {
        ActiveDataRowIndex(-1);

        // Notify
        if (mOptions.onAfterRowActivate) mOptions.onAfterRowActivate();
      }

      // Restore Selected Rows
      if (retainSelectedRows) {
        SetSelectedRowIndexes(oldSelectedRowIndexes, true);
      }
    }

    // ---------------------------------------------------
    // 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");

      // 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: Move active row up in the Grid and Virtual Class
    // --------------------------------------------------------
    function RowMoveUp() {
      // Within range?
      if (mActiveDataRowIndex < 1 || mActiveDataRowIndex >= mVirtualClass.length) 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();
    }

    // ----------------------------------------------------------
    // PUBLIC: Move active row down in the Grid and Virtual Class
    // ----------------------------------------------------------
    function RowMoveDown() {
      // Within range?
      if (mActiveDataRowIndex < 0 || mActiveDataRowIndex >= mVirtualClass.length - 1) 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();
    }

    // -------------------------------
    // 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) {
      var column = GetColumnByKey(key);

      if (column) {
        column.list = null;
        column.collection = null;
        column._collection = null;

        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: 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;

      // 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 && mOptions.sortByColumn == mOptions.groupByColumns) {
        mOptions.groupByDesc = mOptions.sortByDesc;
      }

      // Update
      UpdateElement(false);

      // Restore list index
      ActiveDataRowListIndex(listIndex, true);

      // 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) {
          mOptions.onAfterRowActivate();
        }

        // Notify
        if (mOptions.onSelectedRowsChanged) {
          mOptions.onSelectedRowsChanged({});
        }
      }
    }

    // ----------------------------------------------------------------
    // PUBLIC: Get an array containing the 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
      if (defaultActiveRow && rows.length == 0 && mActiveDataRowIndex >= 0) {
        if (!ignoreExpiredRows || !mVirtualData[mActiveDataRowIndex].expired) {
          rows.push(mActiveDataRowIndex);
        }
      }

      return rows;
    }

    // ------------------------------------------------------
    // PUBLIC: Select rows from the supplied array of 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");
          }
        }
      }

      // Set selected
            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");
        }
      }
    }

    // ---------------------------------------------------------------------------------------------------------
    // 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;
        }
      }
    }


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

      ClearColumns: ClearColumns,
      GetColumnByIndex: GetColumnByIndex,
      GetColumnByKey: GetColumnByKey,

      AddColumnBoolean: AddColumnBoolean,
      AddColumnCurrency: AddColumnCurrency,
      AddColumnDate: AddColumnDate,
      AddColumnDateTime: AddColumnDateTime,
      AddColumnDrilldown: AddColumnDrilldown,
      AddColumnHtml: AddColumnHtml,
      AddColumnIcon: AddColumnIcon,
      AddColumnInteger: AddColumnInteger,
      AddColumnString: AddColumnString,
      AddColumnCode: AddColumnCode,

      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,

      GetSelectedRowIndexes: GetSelectedRowIndexes,
      SetSelectedRowIndexes: SetSelectedRowIndexes,
      //SetRowSelectorIcon: SetRowSelectorIcon,
      SelectAllRows: SelectAllRows,
      GetVirtualDataForSelectedRows: GetVirtualDataForSelectedRows,

      SetColumnCollection: SetColumnCollection,
      SetColumnList: SetColumnList,
      SetColumnListCsv: SetColumnListCsv,

      GroupByColumnsUpdate: GroupByColumnsUpdate,

      ColumnCaption: ColumnCaption,
      ColumnVisible: ColumnVisible,

      Actions: Actions,

      RowMoveUp: RowMoveUp,
      RowMoveDown: RowMoveDown,

      Editing: function () { return mEditing },
      Element: Element,
      ExportData: ExportData,
      Focus: Focus,
      GroupByColumns: GroupByColumns,
      PerformRowDrilldown: PerformRowDrilldown,
      ReadOnly: ReadOnly,
      Refresh: Refresh,
      RefreshButtons: RefreshButtons,
      RefreshRow: RefreshRow,
      RemoveRowAndCollectionItem: RemoveRowAndCollectionItem,
      ResizeFromParent: ResizeFromParent,
      SelectedColumn: SelectedColumn,
      SelectedColumnKey: SelectedColumnKey,
      Sort: Sort,
      Validate: Validate,
      VirtualDataRefresh: VirtualDataRefresh,
      Visible: Visible,
    };

    // 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) {
      // 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;
      }
      mFileUploadSection.append(mFileUploadElement);
      mFileUploadSection.insertBefore(cbe);
    }

    // Initialise
    mComboBox.Visible(true);
    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");
        window.setTimeout(function () {
          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();

        if (mPreviewFileName && !IsNewFile() && mPreviewFileName.toUpperCase() != "[NEW FILE...]") {
          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
      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 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,
      Refresh: Refresh,

      /* 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: 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 DBCombo)
    mComboBox = widget.UI.ComboBox(e, options);
    var ce = mComboBox.Element();
    ce.css("padding-left", "22px");

    // Create Icon Element
    mIconElement = $("<div style='width:16px; height:16px; position:absolute; top:3px; left: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: Information List Combo Box object
  // =========================================
  function InformationListComboBox(e, options) {

    // Use finPOWER Connect Cloud InformationListComboBox (to respect picker panel etc)
    if (!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 = new window.parent.$UI.InformationListComboBox(e, options);
      return c;
    }


    var mComboBox;
    var mInformationList = null;
    var mOptions = options;

    // 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: Set up this Information List
    // ------------------------------------
    function SetComboFromInformationList(informationListId, allowMandatoryOverride, callback, setDefaultValue) {
      // Initialise
      if (allowMandatoryOverride === undefined) allowMandatoryOverride = false;

      // 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
        data = JSON.parse(dataRaw);

        // 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);

          // Resize
          //mComboBox.WidthResizeFromParent(true);
        }

        // Store (required for sectioned lists)
        mInformationList = data;

        // Other properties
        if (allowMandatoryOverride) mComboBox.AllowBlank(!mInformationList.Mandatory);
        mComboBox.LimitToList(mInformationList.LimitToList);
        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);

    }

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

      SetComboFromInformationList: SetComboFromInformationList,
      SetComboFromSectionedInformationList: SetComboFromSectionedInformationList,
      //SetLogOutcomeComboFromSectionedInformationList: SetLogOutcomeComboFromSectionedInformationList,

      /* From DBCombo */
      AllowBlank: mComboBox.AllowBlank,
      AutoReadOnly: mComboBox.AutoReadOnly,
      BlankTip: mComboBox.BlankTip,
      Caption: mComboBox.Caption,
      Focus: mComboBox.Focus,
      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,

      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);
    
    // 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 (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: "inline-block" });
        }
        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("=")) {
          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 += "%";
              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();
      }
    }

    // ---------------
    // 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);
    }

    // --------------------
    // 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();
      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;
      }
    }

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

    // --------------------------
    // 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;

      // Validate?
      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, true, false);
        }
      }
      if (mOptions.maxValue != null) {
        if (s) s += " ";
        s += "to " + Runtime_FormatNumber(mOptions.maxValue, mOptions.decimals, true, 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";
      }
      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,
      Buttons: Buttons,
      ButtonsDefine: ButtonsDefine,
      Caption: Caption,
      Changed: Changed,
      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) {

    // Use finPOWER Connect Cloud ParametersHost (not available outside of finPOWER Connect Cloud)
    if (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 = new window.parent.$UI.ParametersHost(e, options);
      return c;
    }


    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 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,

      smartBackgroundColour: true,

      collapsedCaption: "Preview row",
      border: true,
    };
    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");
      }
    }

    // ------------------------------
    // 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!
      var doc = mContentIframe[0].contentDocument;
      doc.open();
      doc.write("");
      doc.close();

      // 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() {
      return mLoading;
    }

    // ---------------------------------------
    // PUBLIC: Load preview from a Web Service
    // ---------------------------------------
    function PreviewFromWebService(url, params) {
      // Clear (to avoid confusion)
      Clear();

      // Loading
      mLoading = true;
      mPopupCaptionElement.attr("available", false);

      // 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
          // ------
          mLoading = false;
          mPopupCaptionElement.attr("available", true);
        }
      });
    }

    // -----------------------------------------------------------------------------------
    // 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.");
        return;
      }
      else if (!collection.GetPreviewFetchParameters) {
        window.alert("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)
      setTimeout(function () {
        // Row changed?
        if (index != grid.ActiveDataRowListIndex()) return;

        // Loading
        mLoading = true;
        mPopupCaptionElement.attr("available", false);

        // Fetch
        widget.GetString(widgetEventId, collection.GetPreviewFetchParameters(index),
          function (data) {
            // ----
            // Done
            // ----
            var html = data;

            // Cache
            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
            }

            mLoading = false;
            mPopupCaptionElement.attr("available", true);
          },

          function (error) {
            // ----
            // Fail
            // ----
            SetContentError(error);

            mLoading = false;
            mPopupCaptionElement.attr("available", true);
          });
        }, 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;
      mLoading = false;
      mPopupCaptionElement.attr("available", true);

      // 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;
        }

        resourcesHtml += "<link rel='stylesheet' type='text/css' href='" + cssPath + "summarypage_2.css" + suffix + "'></link>";
        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
          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 (window.parent.$Ash) {
          window.parent.$Ash.HandleIframe(mContentIframe[0]);
        }
        else {
          //window.alert("Preview Pane cannot handle Application Shortcuts since no handler ($Ash) is available.");
        }
      }
    }

    // -------------------------------------------------------
    // 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";
      }
      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
    // ------------------------------------
    _self = {
      TypeName: "PreviewPane",

      //CacheAdd: CacheAdd,
      CacheClear: CacheClear,
      CacheExists: CacheExists,
      CacheRemove: CacheRemove,

      Clear: Clear,
      Element: Element,

      Loaded: Loaded,
      Loading: Loading,

      PreviewFromGridCollection: PreviewFromGridCollection,
      //PreviewFromWebService: PreviewFromWebService,

      ResizeFromParent: ResizeFromParent,

      SetContent: SetContent,
      SetContentError: SetContentError,
      //SetContentErrorAjax: SetContentErrorAjax,
      //SetContentFromCache: SetContentFromCache,

      //ShowPreviewInPopup: ShowPreviewInPopup,

      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);
      }

      // 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
    };
    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) {
      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();
        }
      }
    });



    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement() {
      // Caption
      if (mOptions.isHtml) {
        mElement.html(mOptions.text);
      }
      else {
        mElement.html(widget.UI.HtmlEncode(mOptions.text));
      }

      // CSS Classes
      mElement.removeClass();
      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: 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";
      }
      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,

      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());

    // 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.Checkbox.VisibleRow: no parent row element found.")
          mElementRow = null;
          return false;
        }
      }

      if (value === undefined) {
        // Get
        return mElementRow.css("visibility").toUpperCase() == "HIDDEN";
      }
      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 {
        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: Tabs object
  // ===================
  function Tabs(e, options) {
    var mElement;
    var mHeadingElement;
    var mSummaryElement;
    var mOptions;
    var mSelectedTabId = "";
    var mSelectedTabIndex = -1;
    var mTabs;
    var mTabsElement;

    // Extend options with defaults
    TabDefaults = {
      cssClass: "is-tabs",
      pagesParent: null,
      style: "normal",
      visible: true,

      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);

          // 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 Class
      if (mOptions.cssClass) mElement.addClass(mOptions.cssClass);

      // 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");
      }

      // 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);
            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() {
      for (var i = 0; i < mTabs.length; i++) {
        var tab = mTabs[i];

        if (tab.visible) tab.element.show(); else tab.element.hide();

        if (tab.tabId == mSelectedTabId) {
          mSelectedTabIndex = i;
          tab.element.addClass("selected");
          if (tab.pageElement) {
            tab.pageElement.show();
          }
        }
        else {
          tab.element.removeClass("selected");
          if (tab.pageElement) tab.pageElement.hide();
        }
      }
    }

    // ------------------------------
    // 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 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) {
      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();
        }
      }
    }

    // ---------------------------------
    // 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();
    }

    // -----------------------------
    // 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: 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: TabVisible 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: 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();
      }
    }


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

      Element: Element,

      FocusFirst: FocusFirst,

      GetTabById: GetTabById,
      GetTabByIndex: GetTabByIndex,
      GetTabIdByIndex: GetTabIdByIndex,
      GetSelectedPageElement: GetSelectedPageElement,
      Tabs: Tabs,

      RefreshFromArray: RefreshFromArray,

      SelectFirstVisibleTab: SelectFirstVisibleTab,
      SelectedTabId: SelectedTabId,
      SelectedTabIndex: SelectedTabIndex,
      ShowSingleTab: ShowSingleTab,

      TabCount: TabCount,
      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 mBaseScrollHeight;
    var mButtonStrip;
    var mElement;
    var mElementRow;
    var mFocused = false;
    var mIsValid = true;
    var mLabelElement;
    var mOptions;
    var mTagsList = [];
    var mTagsListElement;
    var mTagsListElementParent;
    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: false,

      readOnly: false,
      autoReadOnly: true,

      visible: true,

      width: "auto",
      widthButtonsInclusive: true,
      rows: 1,
      autoExpand: false,
      autoExpandMaxRows: null,

      password: false,

      onChange: null,
      onButtonClick: null,
      onEnterKey: null,

      changeWhileTyping: false,

      hyperlinkContent: false,
      onContentHyperlink: null,
      onFocus: null,

      tagsListElement: null,

      specialType: null,

      dataType: "",         // email, phone
      dataTypeReformat: true, // E.g., if dataType is "phone" then reformat value if necessary

      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]);

    // 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);
    }
    else if (mOptions.password) {
      // Replace with password input
      var password = $("<input type='password' id='" + mElement.attr("id") + "' autocomplete='off' value=''/>");
      mElement.replaceWith(password);
      mElement = password;
    }

    // Wrap element
    if (!mDisableControlStyling) {
      mElement.wrap("<span style='white-space:normal; padding:0; margin:0' controlType='textbox'/>");
      mElement.css("flex-grow", "1");
    }
    mWrapperElement = $(mElement.parent());

    // Actions button element
    mActionsButtonElement = $("<button class='is-control-actions-button'></button>");
    mWrapperElement.append(mActionsButtonElement);
    mActionsButtonElement.click(function () {
      if (mOptions.actionsButtonVisible) {
        if (mOptions.onActionsButtonClick) {
          mOptions.onActionsButtonClick(_self);
        }
        else {
          window.alert("onActionsButtonClick is not handled!");
        }
      }
    });

    // 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]));

    // 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 tags list?
      //TagsListHide();
    });
    mElement.focus(function () {
      mFocused = true;

      // Track focused element for Tags List
      if (mTagsListElement) mTagsListElement.prop("tlt", mElement);
      //TagsListShow();

      // 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();
        }
      });
    }
    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");
      }

      // 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) {
        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();
      }

      // 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-block" });
        }
        else {
          mValidationElement.css({ display: "none" });
        }
      }

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

    // -------------------------
    // PRIVATE: Auto-Expand Rows
    // -------------------------
    function AutoExpand() {
      // NOTE: Not compatible with IE
      if (mBrowserIE) return;

      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;
    }

    // --------------------
    // 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) {
      // Remove validation formatting

      // Bypass validation?
      if (mOptions.readOnly || !Text()) return;

      // Initialise

      // Validate
      switch (mOptions.dataType.toUpperCase()) {
        case "EMAIL":
          // Email (no need for server-side check)
          if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(Text())) {

          }
          break;

        case "PHONE":
          // Phone (server-side check required to validate and optionally, reformat)
          break;
      }
    }

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

    // ----------------------------------
    // PUBLIC: The jQuery Wrapper Element
    // ----------------------------------
    function WrapperElement() {
      return mWrapperElement;
    }

    // -------------
    // PUBLIC: Focus
    // -------------
    function Focus() {
      mElement.focus();
      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 ({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>");
          mWrapperElement.prepend(mTagsListElement);
        }

        mTagsListElementParent = mTagsListElement.parent();

        mElement.attr("tleid", mTagsListElement.attr("tleid"));
        var ul = $("<ul></ul>");
        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
          li.text(tag.caption);
          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 () {
          TagsListShow();
        });
        mTagsListElementParent.focusout(function () {
          TagsListHide();
        });
      }
      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");

        //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");

        //// 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";
      }
      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,
      DataTypeValidate: DataTypeValidate,
      Element: Element,
      Focus: Focus,
      //HyperlinkContent: HyperlinkContent,
      MaxLength: MaxLength,
      ReadOnly: ReadOnly,
      ResizeFromParent: ResizeFromParent,
      TagsListDefine: TagsListDefine,
      Text: Text,
      Visible: Visible,
      VisibleRow: VisibleRow,

      WrapperElement: WrapperElement,
      WidthResizeFromParent: WidthResizeFromParent,

      //IsValid: IsValid,
      //ValidationSet: ValidationSet,

      // Friend
      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: "inline-block" });
        }
        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.Element().remove();
      }
      mCheckBoxes = [];

      // Add checkboxes
      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,

          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: 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);

          // 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";
      }
      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,
      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: Forms sub-object
  // ========================
  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 Range Lookup from a Standard Range
    // -----------------------------------------------
    ShowRangeLookupFromStandardRange: function (rangeName, value, options, doneCallback, failCallback) {
      // Extend options with defaults
      options = $.extend({},
        {
          caption: "",
          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%";

      // Create Modal
      var Modal = widget.UI.Modal({
        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,
      });

      // 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.HandleDocument($(doc));
            $Ash.HandleIframe(contentIframe[0]);
          }
          else {
            window.alert("Show HTML cannot handle Application Shortcuts since no handler ($Ash) is available.");
          }

          //TODO:
          //modal.ContentElement().css({border:"2px solid green", position:"relative"});
        }
        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 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;

        // 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: 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) {
    if (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 < 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) {
    if (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 < 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) {
    // 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) {
    if (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) {
    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) {
    if (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 27: // Escape
            if (options.allowEscape) {
              Modal.Close();
            }
            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
      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: 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) {
        widget.RegisterError("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
    window.setTimeout(function () { 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();
        window.setTimeout(function () { 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;

    // 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 = {
      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) {
        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 showing' 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>");
        $("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 {
            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
      window.setTimeout(function () { 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) {
        window.setTimeout(function () {
          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
      window.setTimeout(function () {
        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;
      }
    }


    // ------------------------------------
    // 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
    };

    // Add to stack
    mModalStack.push(_self);

    return _self;
  }



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

    var mAccountCalc;
    var mConfig = {};
    var mEditStandardTransactionIndex;
    var mElement;
    var mInitialised = false;
    var mOptions;
    var mRecord;

    var C = {
      // Table layout
      trMain: null,
      tdMain: null,
      tblStdTransactions: null,
      tblTermAndPayments: null,
      tblInterest: null,

      // Standard Transactions
      lblStdTransactions: null,
      gridStdTrans: 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,
      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,

      lblInterestRate: null,
      cboInterestType: null,
      numInterestRate: null,
      cboInterestRateTable: null,
      numInterestRatePremium: null,

      lblOtherInterest: null,
      numOtherInterestRate: null,

      // Buttons
      cmdSchedule: null,
      cmdResetFinancial: null,
    };

    // Extend options with defaults
    AccountFinancialDefaults = {
      readOnly: false,
      allowStdTransDrilldown: true,
      allowStdTransReset: true,
      allowReset: true,
      allowSchedule: true,
      autoReadOnly: true,
      showStdTrans: true,
      stdTransWidgetId: "",
      visible: true,

      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 style='border:1px solid rgba(0,0,0,0.025);margin-right:8px;'></div>");
      C.tblStdTransactions = $("<div></div>");
      C.tdMain.append(C.tblStdTransactions);
      C.tblStdTransactions.wrap("<div class='tblStdTransactions'></div>");
    }

    C.tblTermAndPayments = $("<table class='is-form'></table>");
    C.tdMain.append(C.tblTermAndPayments);
    C.tblTermAndPayments.wrap("<div></div>");
    C.tblTermAndPayments.append("<colgroup><col style='width:8em;'/><col/></colgroup>");

    C.tblInterest = $("<table class='is-form'></table>");
    C.tdMain.append(C.tblInterest);
    C.tblInterest.wrap("<div></div>");
    C.tblInterest.append("<colgroup><col style='width:8em;'/><col/></colgroup>");

    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) {
        actions.push({});
        actions.push({ actionId: "StdTransReset", tooltipText: "Reset Transactions to Account Type defaults", icon: "Reset" });
      }
      C.gridStdTrans.Actions().Define(actions);
    }

    //   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: OnChange,
    });

    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,
      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,
      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: false,
      decimals: 4,
      minValue: 0,
      maxValue: 9999,
      onChange: OnChange,
    });


    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,
    });

    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,
      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,
      onChange: OnChange,
    });

    //    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,
      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,
      onChange: OnChange,
    });

    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,
      onChange: OnChange,
    });

    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,
      onChange: OnChange,
    });

    // 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_10,
      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,
      onChange: OnChange,
    });

    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,
      onChange: OnChange,
    });

    //     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,
      onChange: OnChange,
    });

    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,
      onChange: OnChange,
    });

    //     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,
      onChange: OnChange,
    });

    //    Buttons
    if (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.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"); }); }
      }

      // 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("");
        }
      }
    }

    // ------------
    // 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") {
        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) {
              item.ValueCurrency = e.newValue;

              // 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,
      };

      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 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.dateStartupInterestToDate.VisibleRow(false);
            break;

          case "InterestFree":
            C.cboStartupInterestPeriod.VisibleRow(true);
            C.numStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestRateTable.VisibleRow(false);
            C.numStartupInterestRatePremium.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.dateStartupInterestToDate.VisibleRow(false);
            break;

          case "RateTable":
            C.cboStartupInterestPeriod.VisibleRow(true);
            C.numStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestRateTable.VisibleRow(true);
            C.numStartupInterestRatePremium.VisibleRow(true);
            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 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);
            break;

          case "FloatingRate":
            C.numInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestRateTable.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(false);
            break;

          case "InterestFree":
            C.numInterestRate.VisibleRow(false);
            C.cboInterestRateTable.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(false);
            break;

          case "NotApplicable":
            C.numInterestRate.VisibleRow(false);
            C.cboInterestRateTable.VisibleRow(false);
            C.numInterestRatePremium.VisibleRow(false);
            break;

          case "RateTable":
            C.numInterestRate.VisibleRow(false);
            C.cboInterestRateTable.VisibleRow(mConfig.OptionAllowInterest);
            C.numInterestRatePremium.VisibleRow(mConfig.OptionAllowInterest);
            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 "InterestOnly":
          C.numMinimumPaymentValue.VisibleRow(false);
          C.numMinimumPaymentPercent.VisibleRow(false);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(false);
          break;

        case "Instalment":
          C.numMinimumPaymentValue.VisibleRow(false);
          C.numMinimumPaymentPercent.VisibleRow(false);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
          break;

        case "OngoingSetValue":
        case "SetValue":
          C.numMinimumPaymentValue.VisibleRow(true);
          C.numMinimumPaymentPercent.VisibleRow(false);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
          break;

        case "PercentOfBalance":
          C.numMinimumPaymentValue.VisibleRow(false);
          C.numMinimumPaymentPercent.VisibleRow(true);
          C.cboMinimumPaymentHoldToPeriod.VisibleRow(mConfig.OptionAllowMinimumPaymentHoldTo);
          break;

        default:
          C.numMinimumPaymentValue.VisibleRow(true);
          C.numMinimumPaymentPercent.VisibleRow(true);
          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 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 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") {
        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();
    }

    // ------------------
    // Update the Element
    // ------------------
    function UpdateElement(refetchWarningMessage) {
      // 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

        // 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.lblStartupInterestRate.VisibleRow(false);
            C.cboStartupInterestType.VisibleRow(false);
            C.cboStartupInterestPeriod.VisibleRow(false);
            C.numStartupInterestRate.VisibleRow(false);
            C.numStartupInterestRatePremium.VisibleRow(false);
            C.dateStartupInterestToDate.VisibleRow(false);

            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.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);

            if (C.cmdSchedule) C.cmdSchedule.hide();
            if (C.cmdResetFinancial) C.cmdResetFinancial.hide();
            break;

          case "LoanFT":
            // ----------
            // Fixed Term
            // ----------
            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.cboPaymentFirstDatePeriod.VisibleRow(mConfig.OptionAllowFirstPaymentDate);
            //C.datePaymentFirstDate.VisibleRow(mConfig.OptionAllowFirstPaymentDate);
            //C.numPaymentRegular.VisibleRow(mConfig.OptionAllowRegularPayment);
            //C.numPaymentBalloon.VisibleRow(mConfig.OptionAllowBalloonPayment);

            //C.lblResidualValue.VisibleRow(mConfig.OptionAllowResidualValue);
            //C.numResidualValue.VisibleRow(mConfig.OptionAllowResidualValue);

            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);

            if (C.cmdSchedule) C.cmdSchedule.show();
            if (C.cmdResetFinancial) C.cmdResetFinancial.show();
            break;

          case "LoanFR":
            // -------------
            // Floating Rate
            // -------------
            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.cboPaymentFirstDatePeriod.VisibleRow(mConfig.OptionAllowFirstPaymentDate);
            //C.datePaymentFirstDate.VisibleRow(mConfig.OptionAllowFirstPaymentDate);
            //C.numPaymentRegular.VisibleRow(mConfig.OptionAllowRegularPayment);
            //C.numPaymentBalloon.VisibleRow(mConfig.OptionAllowBalloonPayment);

            //C.lblResidualValue.VisibleRow(mConfig.OptionAllowResidualValue);
            //C.numResidualValue.VisibleRow(mConfig.OptionAllowResidualValue);

            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);

            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.lblStartupInterestRate.VisibleRow(false);
            //C.cboStartupInterestType.VisibleRow(false);
            //C.cboStartupInterestPeriod.VisibleRow(false);
            //C.numStartupInterestRate.VisibleRow(false);
            //C.numStartupInterestRatePremium.VisibleRow(false);
            //C.dateStartupInterestToDate.VisibleRow(false);

            C.lblInterestRate.VisibleRow(mConfig.OptionAllowInterest);
            C.cboInterestType.VisibleRow(mConfig.OptionAllowInterest);

            if (C.cmdSchedule) C.cmdSchedule.show();
            if (C.cmdResetFinancial) C.cmdResetFinancial.show();
            break;

          default:
            console.warn("widget_ui.AccountFinancial: AccountClass '" + mRecord.AccountClass + "' not handled.");
        }
      }
    }

    //// ------------------
    //// 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) {
      // 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);

          C.cboPaymentFirstDatePeriod.VisibleRow(mConfig.OptionAllowFirstPaymentDate);
          C.datePaymentFirstDate.VisibleRow(mConfig.OptionAllowFirstPaymentDate);
          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 + ":");

          // 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);
          }
          else {
            C.lblMinimumPayments.VisibleRow(false);
            C.cboMinimumPaymentBasis.VisibleRow(false);
            C.numMinimumPaymentValue.VisibleRow(false);
            C.numMinimumPaymentPercent.VisibleRow(false);
            C.cboMinimumPaymentHoldToPeriod.VisibleRow(false);
          }
            //C.numMinimumPaymentValue.VisibleRow(false);
            //C.numMinimumPaymentPercent.VisibleRow(false);
            //C.dateMinimumPaymentInstalmentEndDate.VisibleRow(false);
            //C.numMinimumPaymentInstalmentResidualValue.VisibleRow(false);
            //C.numMinimumPaymentDueDays.VisibleRow(false);
            //C.chkMinimumPaymentDueDaysOverride.VisibleRow(false);
            //C.cboMinimumPaymentHoldToPeriod.VisibleRow(false);
            //C.dateMinimumPaymentHoldToDate.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");

          // Startup 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.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
          C.lblOtherInterest.VisibleRow(mConfig.OtherInterestShow);
          C.numOtherInterestRate.VisibleRow(mConfig.OtherInterestShow);
        }
        else {
          mConfig = {};
          console.warn("widget_ui.AccountFinancial: FromAccountCalcJson does not contain a Config object to enable configuration such as Term Entry Method");
        }

        // 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);

        // Minimum Payments
        C.cboMinimumPaymentBasis.Text(o.MinimumPaymentBasisText);
        cboMinimumPaymentBasis_Change();
        C.numMinimumPaymentValue.Value(o.MinimumPaymentValue);
        C.numMinimumPaymentPercent.Value(o.MinimumPaymentPercent);
        C.cboMinimumPaymentHoldToPeriod.Text(o.MinimumPaymentHoldToPeriod);
        cboMinimumPaymentHoldToPeriod_Change();
        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);
        }
        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);

        // Interest Rate
        C.cboInterestType.Text(o.InterestTypeText);
        C.numInterestRate.Value(o.InterestRate);
        C.cboInterestRateTable.Text(o.InterestRateTableId);
        C.numInterestRatePremium.Value(o.InterestRatePremium);

        // Other Interest
        C.numOtherInterestRate.Value(o.OtherInterestRate);

        // 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);
            }
          }
        }
      }
    }

    // -----------------------------------
    // 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 = "";
      }

      // 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.MinimumPaymentValue = C.numMinimumPaymentValue.Value();
      o.MinimumPaymentPercent = C.numMinimumPaymentPercent.Value();
      o.MinimumPaymentHoldToPeriod = C.cboMinimumPaymentHoldToPeriod.Text();
      o.MinimumPaymentHoldToDate = C.dateMinimumPaymentHoldToDate.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();
      //o.

      // 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();

      // Standard Transactions
      o.StdTrans = mRecord.StdTrans;

      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 Term Cycle
    // ----------------------
    function TermCycle() {
      return C.cboTermCycle.Text();
    }

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

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

      FromAccountCalcJson: FromAccountCalcJson,
      ToAccountCalc: ToAccountCalc,
      ToAccountCalcJson: ToAccountCalcJson,

      InterestPaymentType: InterestPaymentType,
      TermCycle: TermCycle,
    };
    return _self;
  }



  // ====================================
  // Return PUBLIC methods and properties
  // ====================================
  var _self =
  {
    Block: Block,
    Unblock: Unblock,

    ApplyIcons: ApplyIcons,

    DisableControlStyling: DisableControlStyling,

    DDListFromArray: DDListFromArray,
    DDListFromCollection: DDListFromCollection,
    DDListFromCsv: DDListFromCsv,
    DDListAdd: DDListAdd,

    HtmlEncode: HtmlEncode,
    ScrollToTop: ScrollToTop,

    InitialiseAddressAutoComplete: InitialiseAddressAutoComplete,

    IsSmallMobileBrowser: IsSmallMobileBrowser,

    TableAddRowsFromCollection: TableAddRowsFromCollection,

    ValidateContainer: ValidateContainer,
    Evaluate: Evaluate,

    AccountFinancial: AccountFinancial,
    AccountPaymentDetails: AccountPaymentDetails,
    AccountIncomingPaymentDetails: AccountIncomingPaymentDetails,
    AccountOutgoingPaymentDetails: AccountOutgoingPaymentDetails,
    AddressDetails: AddressDetails,
    ButtonList: ButtonList,
    ButtonStrip: ButtonStrip,
    CheckBox: CheckBox,
    CheckList: CheckList,
    ComboBox: ComboBox,
    DashboardLayout: DashboardLayout,
    DateBox: DateBox,
    DateCycleComboBox: DateCycleComboBox,
    DBCombo: DBCombo,
    DocumentManagerComboBox: DocumentManagerComboBox,
    DropdownPanel: DropdownPanel,
    Form: Form,
    Grid: Grid,
    IconComboBox: IconComboBox,
    InformationListComboBox: InformationListComboBox,
    Label: Label,
    Modal: Modal,
    NumberBox: NumberBox,
    ParametersHost: ParametersHost,
    PreviewPane: PreviewPane,
    PromptUpdateList: PromptUpdateList,
    RadioButton: RadioButton,
    RadioButtonList: RadioButtonList,
    RangeSlider: RangeSlider,
    Tabs: Tabs,
    TextBox: TextBox,

    Forms: mForms,

    ModalOpenCount: ModalOpenCount,
    GetModalById: GetModalById,

    MsgBoxAlert: MsgBoxAlert,
    MsgBoxConfirm: MsgBoxConfirm,
    MsgBoxConfirmList: MsgBoxConfirmList,
    MsgBoxConfirmDelete: MsgBoxConfirmDelete,
    MsgBoxInfo: MsgBoxInfo,
    MsgBoxList: MsgBoxList,

    GetControlRow: GetControlRow,

    LoadStyle: LoadStyle,
    StyleAsModal: StyleAsModal,

    // Constants
    FIELD_WIDTH_CODE_5: "6em",
    FIELD_WIDTH_CODE_10: "9em",
    FIELD_WIDTH_CODE_15: "12em",
    FIELD_WIDTH_CODE_20: "16em",

    // 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,
    };
    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 () {
      // 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);
      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;
  };
})($);