﻿/*
#################################################################
 DO NOT MODIFY THIS FILE UNDER ANY CIRCUMSTANCES
#################################################################

 Copyright Intersoft Systems Limited. All Rights Reserved

 Widget shared v1.32.01 (7-Dec-2023)

 NOTE: This contains only shared, generic code.

       Where possible, this will call directly into Runtime since
       this is the finPOWER Connect Cloud implementation.
#################################################################
*/
console.log("Loading widget.js (generic)");

window.__widgetGeneric = function () {

  var mGraphicsInfo = "";
  var mIsApp = false;
  var mIsApp_Android = false;
  var mIsApp_iOS = false;
  var mIs_iOS = false;
  var Runtime = null;

  // Graphics detection
  // Thanks to: https://51degrees.com/blog/missing-ipad-tablet-web-traffic
  var canvas = document.createElement("canvas");
  if (canvas != null) {
    var context = canvas.getContext("webgl") ||
      canvas.getContext("experimental-webgl");
    if (context) {
      var info = context.getExtension(
        "WEBGL_debug_renderer_info");
      if (info) mGraphicsInfo = context.getParameter(info.UNMASKED_RENDERER_WEBGL);
    }
  }

  // App detection
  // Ref: https://stackoverflow.com/questions/37591279/detect-if-user-is-using-webview-for-android-ios-or-a-regular-browser
  var userAgent = window.navigator.userAgent.toLowerCase();
  var safari = /safari/.test(userAgent);
  mIs_iOS = mGraphicsInfo == "Apple GPU" || /iphone|ipod|ipad/.test(userAgent);
  if (mIs_iOS) {
    if (safari) {
      // Browser
    }
    else {
      mIsApp_iOS = true;
    }
  }
  else {
    if (userAgent.indexOf("wv") != -1) {
      mIsApp_Android = true;
    }
  }
  mIsApp = mIsApp_iOS || mIsApp_Android;

  // Get Runtime (if running from finPOWER Connect Cloud)
  if (window.parent) {
    try {
      Runtime = window.parent.$Runtime;

      // Keep finPOWER Connect Cloud Session Alive when Widget is interacted with
      if (Runtime) {
        if (window.parent.$App) {
          $(window).on("mousedown keydown mousemove", function () {
            window.parent.$App.WidgetNotifyBusy(true);
          });
        }
      }
    }
    catch (ex) {
      // Probably a Portal hosted in an IFRAME and browser security is protecting the parent frame
    }
  }

  // ============================================
  // PUBLIC: Add a GetItem(id) method to an array
  // ============================================
  function ArrayAllowLookupById(array, idPropertyName) {
    array.GetItem = function (id) {
      // Initialise
      id = ("" + id).toUpperCase();
      // Find
      for (var i = 0; i < array.length; i++) {
        if (id === array[i][idPropertyName].toUpperCase()) {
          return array[i];
        }
      }
      return null;
    };
  }

  // ====================================
  // PUBLIC: Remove an item from an array
  // ====================================
  function ArrayRemove(array, item) {
    var i = array.indexOf(item);
    if (i !== -1) {
      array.splice(i, 1);
    }
  }

  // ==================================================
  // PUBLIC: Compare Two Dates (excluding time portion)
  //
  // Returns:
  //  0         - match
  //  1         - date1 higher
  //  -1        - date2 higher
  //  2         - no match but either date1 or date2 are not dates
  // ==================================================
  function CompareDates(date1, date2) {
    // Undefined, null etc?
    if (!date1 && !date2) return 0;
    if (!date1 || !date2) return 2;

    // Ensure dates
    date1 = new Date(date1);
    date2 = new Date(date2);

    // Another invalid date check
    if (!date1.getFullYear() && !date2.getFullYear()) return 0;
    if (!date1.getFullYear() || !date2.getFullYear()) return 2;

    if (date1.getFullYear() === date2.getFullYear() && date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate()) {
      return 0;
    }
    else if (date1.getTime() > date2.getTime()) {
      return 1;
    }
    else {
      return -1;
    }
  }

  // ======================================================
  // PUBLIC: Enhance an array into a Code/ Description List
  // ======================================================
  function ArrayToCodeDescriptionList(array) {
    if (array && Array.isArray(array)) {
      // ToDescriptionCsvList
      array.ToDescriptionCsvList = function () {
        var s = "";
        for (var i = 0; i < array.length; i++) {
          if (s) s += ",";
          s += array[i].Description;
        }
        return s;
      };

      // CodeToDescription
      array.CodeToDescription = function (value) {
        for (var i = 0; i < array.length; i++) {
          if (array[i].Code.toUpperCase() == value.toUpperCase()) {
            return array[i].Description;
          }
        }
        return "";
      };

      // DescriptionToCode
      array.DescriptionToCode = function (value) {
        for (var i = 0; i < array.length; i++) {
          if (array[i].Description.toUpperCase() === value.toUpperCase()) {
            return array[i].Code;
          }
        }
        return "";
      };
    }
  }

  // ================================================
  // PUBLIC: Round a number to the specified decimals
  // ================================================
  function Round(number, precision) {
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round

    var shift = function (number, exponent) {
      var numArray = ("" + number).split("e");
      return +(numArray[0] + "e" + (numArray[1] ? (+numArray[1] + exponent) : exponent));
    };
    return shift(Math.round(shift(number, +precision)), -precision);
  }

  // ==============================================================================
  // PUBLIC: Rounds a currency value to the next smallest value. Note: .5 rounds up
  // ==============================================================================
  function RoundCurrency(value) {
    var currencyDigits = Runtime ? Runtime.CurrencyDecimals() : _config.currencyDecimals;
    var multiplier;

    switch (currencyDigits) {
      case 0:
        multiplier = 1;

        if (value < 0) {
          // Reverse sign if negative
          return -Math.floor(-value * multiplier + 0.5);
        }
        else {
          return Math.floor(value * multiplier + 0.5);
        }
        break;

      case 2:
        multiplier = 100;

        if (value < 0) {
          // Reverse sign if negative
          return -Math.floor(-value * multiplier + 0.5) / multiplier;
        }
        else {
          return Math.floor(value * multiplier + 0.5) / multiplier;
        }
        break;

      default:
        console.warn("widget.RoundCurrency: Only designed to be used with currency decimals of 0 or 2.");
        return Round(value, currencyDecimals);
    }
  }

  // ===============================================================
  // PUBLIC: Rounds a currency value DOWN to the next smallest value
  // ===============================================================
  function RoundCurrencyDown(value) {
    var currencyDigits = Runtime ? Runtime.CurrencyDecimals() : _config.currencyDecimals;
    var multiplier;

    switch (currencyDigits) {
      case 0:
        multiplier = 1;

        if (value < 0) {
          // Reverse sign if negative
          return -Math.floor(-value * multiplier);
        }
        else {
          return Math.floor(value * multiplier);
        }
        break;

      case 2:
        multiplier = 100;

        if (value < 0) {
          // Reverse sign if negative
          return -Math.floor(-value * multiplier) / multiplier;
        }
        else {
          return Math.floor(value * multiplier) / multiplier;
        }
        break;

      default:
        console.warn("widget.RoundCurrencyDown: Only designed to be used with currency decimals of 0 or 2.");

        multiplier = Math.pow(10, currencyDigits);

        if (value < 0) {
          // Reverse sign if negative
          return -Math.floor(-value * multiplier) / multiplier;
        }
        else {
          return Math.floor(value * multiplier) / multiplier;
        }
    }
  }

  // =============================================================
  // PUBLIC: Rounds a currency value UP to the next smallest value
  // =============================================================
  function RoundCurrencyUp(value) {
    var currencyDigits = Runtime ? Runtime.CurrencyDecimals() : _config.currencyDecimals;
    var value2 = RoundCurrencyDown(value);

    if (value2 == value) {
      return value2;
    }
    else {
      // Need to round up one unit
      switch (currencyDigits) {
        case 0:
          return RoundCurrencyDown(value + 1);

        case 2:
          return RoundCurrencyDown(value + 1 / 100);

        default:
          console.warn("widget.RoundCurrency: Only designed to be used with currency decimals of 0 or 2.");
          return RoundCurrencyDown(value + 1 / Math.pow(10, currencyDigits));
      }
    }
  }

  // ======================================
  // PUBLIC: Add Days to the specified date
  // ======================================
  function DateAddDays(date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    return d;
  }

  // ======================================================
  // PUBLIC: Format a Credit Card Expiry Date from a String
  // ======================================================
  function FormatCardExpiryDate(s) {
    var y = new Date().getFullYear();
    var m = new Date().getMonth() + 1;
    var um;
    var uy;

    // Extract month and year
    s += "";
    var n = s.indexOf("/");
    if (n == -1) n = s.indexOf("\\");
    if (n == -1) n = s.indexOf("-");
    if (n == -1) n = s.indexOf(" ");
    if (n == -1 && (s.length == 4 || s.length == 6)) {
      // No separator, e.g., 0922
      um = s.substr(0, 2);
      uy = s.substr(2);
    }
    else if (n == -1) {
      return "";
    }
    else {
      // With separator, e.g., 09/22
      um = parseInt(s.substr(0, n));
      uy = parseInt(s.substr(n + 1));
    }

    // Validate
    if (um < 0 || um > 12 || uy < 0 || uy > 9999) {
      return "";
    }

    // Format
    var sm = "" + um;
    var sy = "" + uy;
    if (sy.length == 1) {
      sy = ("" + y).substr(0, 2) + "0" + sy;
    }
    else if (sy.length == 2) {
      sy = ("" + y).substr(0, 2) + sy;
    }
    if (sm.length == 1) sm = "0" + sm;

    return sm + "/" + sy;
  }

  // =============================
  // PUBLIC: Format Currency value
  // =============================
  function FormatCurrency(n, includeSymbol, blankIfZero, forceMinusSymbol) {
    if (Runtime) {
      // finCC
      return Runtime.FormatCurrency(n, includeSymbol, blankIfZero, forceMinusSymbol);
    }
    else {
      if (n == 0 && blankIfZero) return "";

      // Initialise
      var s = FormatNumberInternal(n, -1, true, false);

      // Negative currency value?
      if (n < 0) s = s.substr(1);

      // Finalise
      if (includeSymbol) s = _config.currencySymbol + s;

      // Negative currency value?
      if (n < 0) {
        if (forceMinusSymbol) {
          s = "-" + s;
        }
        else {
          s = "(" + s + ")";
        }
      }

      return s;
    }
  }

  // ===================
  // PUBLIC: Format Date
  // ===================
  function FormatDate(d) {
    if (Runtime) {
      // finCC
      return Runtime.FormatDate(d, false, false, false);
    }
    else {
      return FormatDateInternal(d);
    }
  }

  // ============================================
  // PUBLIC: Format a Date showing the UTC values
  // ============================================
  function FormatUtcDate(d) {
    if (Runtime) {
      // finCC
      return Runtime.FormatDate(d, false, false, true);
    }
    else {
      return FormatDateInternal(d, null, true);
    }
  }

  // ============================
  // PUBLIC: Format Date and Time
  // ============================
  function FormatDateTime(d, omitTimeIfMidnight) {
    if (Runtime) {
      // finCC
      return Runtime.FormatDate(d, true, false, false);
    }
    else {
      return FormatDateInternal(d, _config.dateFormat + " " + _config.timeFormat);
    }
  }

  // =====================================================
  // PUBLIC: Format a Date and Time showing the UTC values
  // =====================================================
  function FormatUtcDateTime(d) {
    if (Runtime) {
      // finCC
      return Runtime.FormatDate(d, true, false, true);
    }
    else {
      return FormatDateInternal(d, _config.dateFormat + " " + _config.timeFormat, true);
    }
  }

  // =======================================================================
  // PUBLIC: Format Date for displaying in a grid
  //
  // NOTE: Assumes the date is a UTC date and should display UTC values also
  // =======================================================================
  function FormatDateForGrid(d, includeTime, longTime) {
    if (!longTime) longTime = false;

    if (Runtime) {
      // finCC
      return Runtime.FormatDateForGrid(d, includeTime, false, true, longTime); // Do not convert to UTC but do display UTC values
    }
    else {
      if (includeTime) {
        if (longTime) {
          return FormatDateInternal(d, _config.dateFormatGrid + " " + "HH:mm:ss", true);
        }
        else {
          return FormatDateInternal(d, _config.dateFormatGrid + " " + _config.timeFormatGrid, true);
        }
      }
      else {
        return FormatDateInternal(d, _config.dateFormatGrid, true);
      }
    }
  }

  // =======================
  // PUBLIC: Format a Number
  // =======================
  function FormatNumber(value, decimals, showSeparators, blankIfZero) {
    if (Runtime) {
      // finCC
      return Runtime.FormatNumber(value, decimals, showSeparators, blankIfZero);
    }
    else {
      return FormatNumberInternal(value, decimals, showSeparators, blankIfZero);
    }
  }

  // ------------------------
  // PRIVATE: Format a Number
  // ------------------------
  function FormatNumberInternal(n, decimals, showSeparators, blankIfZero) {
    var currency = false;

    // Shortcut
    if (n === 0 && blankIfZero) return "";

    // Initialise
    if (decimals === -1) {
      decimals = _config.currencyDecimals;
      currency = true;
    }
    if (n === null || n === "" || isNaN(n)) n = 0;

    // Fix Decimal Places
    n = parseFloat(n);
    var s = n.toFixed(decimals) + '';

    // Comma-separators
    if (showSeparators) {
      s += '';
      var x = s.split('.');
      var x1 = x[0];
      var x2 = x.length > 1 ? '.' + x[1] : '';
      var r = /(\d+)(\d{3})/;
      while (r.test(x1)) {
        x1 = x1.replace(r, '$1' + ',' + '$2');
      }
      s = x1 + x2;
    }

    // Finalise
    if (s === 0 && blankIfZero)
      return "";
    else
      return s;
  }

  // -------------------------------------------------------------
  // PUBLIC: Format a Time value, i.e., the time portion of a date
  //
  // NOTE: For input therefore always HH:mm:ss
  // -------------------------------------------------------------
  function FormatTime(d, blankIfMidnight, showUtcValues) {
    if (d) {
      if (showUtcValues) {
        // Show actual values stored in the UTC date, i.e., do not convert to local
        if (blankIfMidnight && d.getUTCHours() === 0 && d.getUTCMinutes() === 0 && d.getUTCSeconds() === 0) {
          return "";
        }
        else {
          return FormatDateInternal(d, "HH:mm:ss", showUtcValues);
        }
      }
      else {
        // Get values from the date in a way that will convert UTC to local
        if (blankIfMidnight && d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0) {
          return "";
        }
        else {
          return FormatDateInternal(d, "HH:mm:ss");
        }
      }
    }
    else {
      return "";
    }
  }

  // ---------------------
  // FRIEND: Format a Date
  // ---------------------
  function FormatDateInternal(d, dateFormat, showUtcValues) {
    if (d) {
      // Convert from ISO 8601 String?
      if (typeof d === "string") {
        d = new Date(d);
      }

      // Initialise
      var s = dateFormat;
      if (!s) {
        if (Runtime) {
          // finCC
          s = Runtime.DateFormat();
        }
        else {
          s = _config.dateFormat;
        }
      }

      // Tidy up date format (just in case! - J030516)
      while (s.indexOf("MMM") != -1) {
        s = s.replace("MMM", "MM");
      }

      // Date
      if (showUtcValues) {
        s = s.replace("dd", ("0" + d.getUTCDate()).slice(-2));
        s = s.replace("d", d.getUTCDate());
        s = s.replace("MM", ("0" + (d.getUTCMonth() + 1)).slice(-2));
        s = s.replace("M", d.getUTCMonth() + 1);
        var y = d.getUTCFullYear();
        s = s.replace("yyyy", y);
        s = s.replace("yy", (y + "").substr(2));
      }
      else {
        s = s.replace("dd", ("0" + d.getDate()).slice(-2));
        s = s.replace("d", d.getDate());
        s = s.replace("MM", ("0" + (d.getMonth() + 1)).slice(-2));
        s = s.replace("M", d.getMonth() + 1);
        var y = d.getFullYear();
        s = s.replace("yyyy", y);
        s = s.replace("yy", (y + "").substr(2));
      }

      // Time
      var sec, m, h, hs;
      if (showUtcValues) {
        sec = d.getUTCSeconds();
        m = d.getUTCMinutes();
        h = d.getUTCHours();
      }
      else {
        sec = d.getSeconds();
        m = d.getMinutes();
        h = d.getHours();
      }
      hs = h;
      if (hs > 12) hs -= 12;
      s = s.replace("HH", ("0" + h).slice(-2));
      s = s.replace("H", h);
      s = s.replace("hh", ("0" + hs).slice(-2));
      s = s.replace("h", hs);
      s = s.replace("mm", ("0" + m).slice(-2));
      s = s.replace("m", m);
      s = s.replace("ss", ("0" + sec).slice(-2));
      s = s.replace("s", sec);
      if (h < 12) {
        s = s.replace("tt", "a.m.");
        s = s.replace("t", "a");
      }
      else {
        s = s.replace("tt", "p.m.");
        s = s.replace("t", "p");
      }

      return s;
    }
    else {
      return "";
    }
  }

  // =======================================
  // FRIEND: Intersoft flag for internal use
  // =======================================
  function IsClientManagement() {
    if (window.parent && window.parent.$App) {
      return window.parent.$App.WidgetOptions().isClientManagement;
    }
    else {
      return false;
    }
  }

  // ===========================
  // PUBLIC: Get Hosting Context
  // ===========================
  function GetHostingContext() {
    if (Runtime) {
      // finCC
      return "WebInternal";
    }
    else if (window._config && _config.desktop) {
      // finPOWER Connect Desktop
      return "HtmlViewer";
    }
    else {
      // Must be externally hosted
      return "WebExternal";
    }
  }

  // =======================================================
  // PUBLIC: Get Day of the Week Text given a dayIndex (0-6)
  // =======================================================
  function GetWeekDayName(dayIndex, abbreviate) {
    var day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][dayIndex % 7];

    if (abbreviate) {
      return day.substring(0, 3);
    }
    else {
      return day;
    }
  }

  // =============================================
  // PUBLIC: Get Day of the Week Text given a Date
  // =============================================
  function GetWeekDayNameFromDate(date, abbreviate) {
    if (date && typeof date === "string") {
      // Convert from ISO 8601 String?
      date = new Date(date);
    }

    if (!date || !date.getDay) return "";

    return GetWeekDayName(date.getDay(), abbreviate);
  }

  // ======================================
  // PUBLIC: Get Age Text at a given a Date
  // ======================================
  function GetAgeText(date, dateAsAt, full) {
    if (!date || !date.getDay) return "";
    if (!dateAsAt) {
      var d = new Date();
      dateAsAt = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    }
    if (CompareDates(date, dateAsAt) >= 0) return "";

    // Calculate Age
    var o = CalculateAgeInternal(date, dateAsAt);
    var age = "";

    if (o.years > 0 || full) {
      if (o.years === 1)
        age += "1 year";
      else
        age += o.years + " years";
    }
    if (o.months !== 0 && (o.years < 5 || full)) {
      if (age) age += " ";
      if (o.months === 1)
        age += "1 month";
      else
        age += o.months + " months";
    }
    if (o.days !== 0 && (o.years < 1 || full)) {
      if (age) age += " ";
      if (o.days === 1)
        age += "1 day";
      else
        age += o.days + " days";
    }

    return age;
  }

  function CalculateAgeInternal(date, dateAsAt) {
    var one_day = 1000 * 60 * 60 * 24;

    // Get an estimate (always less than/ equal to end result)
    var monthsDifference = ((dateAsAt.getFullYear() - date.getFullYear()) * 12) + (dateAsAt.getMonth() - date.getMonth()) - 1;
    var days;

    // Increase count until found
    days = -1;
    var counter = 0;
    while (true) {
      var date3 = new Date(date.getUTCFullYear(), date.getUTCMonth() + monthsDifference, date.getUTCDate());

      // Gone too far?
      if (CompareDates(date3, dateAsAt) === 1) {
        monthsDifference -= 1;
        if (days !== -1) break;

        // Development test - should never get here
        console.warn("widget.CalculateAgeInternal: Unexpectedly reached block A!");
        monthsDifference -= 1;
      }

      // Calculate days
      days = Math.floor((dateAsAt - date3) / one_day);

      // Simple test to see if found
      if (days >= 0 && days < 28) break;

      // Try the next month
      monthsDifference += 1;

      // Just in case!
      counter += 1;
      if (counter > 100) {
        console.warn("widget.CalculateAgeInternal: Unexpectedly reached block B!");
        break;
      }
    }

    var years = Math.floor(monthsDifference / 12);
    var months = monthsDifference - (years * 12);

    return { years: years, months: months, days: days};
  }

  // ==========================================
  // PUBLIC: Get Age in Years at a given a Date
  // ==========================================
  function GetAgeInYears(date, dateAsAt) {
    if (!date || !date.getDay) return 0;
    if (!dateAsAt) {
      var d = new Date();
      dateAsAt = new Date(d.getFullYear(), d.getMonth(), d.getDate());
    }
    if (CompareDates(date, dateAsAt) >= 0) return 0;

    // Calculate Age
    var o = CalculateAgeInternal(date, dateAsAt);

    // Returns Years
    return o.years;
  }

  // =========================================================================
  // PUBLIC: Check if the specified Colour (#RRGGBB) should be considered Dark
  // =========================================================================
  function IsColourDark(hex) {
    // Get RGB
    try {
      var r = parseInt("0x" + hex.substr(1, 2));
      var g = parseInt("0x" + hex.substr(3, 2));
      var b = parseInt("0x" + hex.substr(5, 2));
    }
    catch (ex) {
      // Ignore
      return false;
    }

    return 299 * r + 587 * g + 114 * b < 128000;
  }

  // ==========================================================================
  // PUBLIC: Check if the specified Colour (#RRGGBB) should be considered Light
  // ==========================================================================
  function IsColourLight(hex) {
    return !IsColourDark(hex);
  }

  // ==================================
  // PUBLIC: Is this a High DPI device?
  // ==================================
  function IsHighDpi() {
    return window.devicePixelRatio > 1.25;
  }

  // ======================================================
  // PUBLIC: Parse a Date string into a Date object or null
  // ======================================================
  function ParseDate(s, historic, displayValuesAreUtc) {
    var dp, d = 0, m = 0, y = 0, temp;

    // Initialise
    if (s) s = s.toUpperCase();

    // Blank
    if (!s) return null;

    // Special
    if (s === "NOW" || s === "TODAY") {
      // Format a date for parsing (so issues with UTC and parsing can all be sorted centrally, i.e., below
      s = FormatDate(new Date(), false, false, false);
    }

    // Contains letters (month names) so parse locally
    if (s.match(/[a-zA-Z]/) != null) {
      // If no numbers on the end then append the current year
      if ("0123456789".indexOf(s.substr(s.length - 1, 1)) == -1) {
        s += " " + new Date().getFullYear();
      }

      // Parse
      d = Date.parse(s);
      if (d) {
        // Format a date for parsing (so issues with UTC and parsing can all be sorted centrally, i.e., below
        s = FormatDate(new Date(d), false, false, false);
      }
      else {
        return null;
      };
    }

    // All numeric so parse differently
    if (/^\d+$/.test(s)) {
      var baseDate = new Date(), baseYear2;
      var dblTemp, d, m, y;

      dblTemp = parseFloat(s);
      baseYear2 = baseDate.getFullYear();
      baseYear2 -= Math.floor(baseYear2 / 100) * 100;

      if (dblTemp === 0) {
        d = 0;
        m = 0;
        y = 0;
      }
      else if (dblTemp < 100) {
        // Assume Day entered
        d = dblTemp;
        m = baseDate.getMonth() + 1;
        y = baseDate.getFullYear();
      }
      else if (dblTemp < 10000) {
        // Assume Day+Month entered (use date order)
        if (_config.dayMonthYearOrder.indexOf("D") < _config.dayMonthYearOrder.indexOf("M")) {
          // Assume Day+Month
          d = Math.floor(dblTemp / 100);
          m = Math.floor(dblTemp - (d * 100));
        }
        else {
          // Assume Month+Day
          m = Math.floor(dblTemp / 100);
          d = Math.floor(dblTemp - (m * 100));
        }
        y = baseDate.getFullYear();
        if (baseDate.getMonth() < 2 && m > 10) {
          y -= 1;
        }
        else if (baseDate.getMonth() > 9 && m < 3) {
          y += 1;
        }
      }
      else if (dblTemp < 1000000) {
        // Assume 2-digit Year included
        switch (_config.dayMonthYearOrder) {
          case "DMY":
            m = Math.floor(dblTemp / 100);
            y = Math.floor(dblTemp - (m * 100));
            if (y < 100) {
              var bc = Math.floor(baseDate.getFullYear() / 100) * 100;
              if (historic && y > baseYear2) bc -= 100;
              y += bc;
            }
            d = Math.floor(m / 100);
            m -= (d * 100);
            break;

          case "MDY":
            d = Math.floor(dblTemp / 100);
            y = Math.floor(dblTemp - (d * 100));
            if (y < 100) {
              var bc = Math.floor(baseDate.getFullYear() / 100) * 100;
              if (historic && y > baseYear2) bc -= 100;
              y += bc;
            }
            m = Math.floor(d / 100);
            d -= (m * 100);
            break;

          case "YMD":
            // Not implemented
            window.alert("YMD date order not implemented");
            break;
        }
      }
      else if (dblTemp < 100000000) {
        // Assume 4-digit Year included
        switch (_config.dayMonthYearOrder) {
          case "DMY":
            m = Math.floor(dblTemp / 10000);
            y = Math.floor(dblTemp - (m * 10000));
            d = Math.floor(m / 100);
            m -= (d * 100);
            break;

          case "MDY":
            d = Math.floor(dblTemp / 10000);
            y = Math.floor(dblTemp - (d * 10000));
            m = Math.floor(d / 100);
            d -= (m * 100);
            break;

          case "YMD":
            // Not implemented
            window.alert("YMD date order not implemented");
            break;
        }
      }
      else {
        d = 0;
        m = 0;
        y = 0;
      }

      // Validate (so we don't get random looking dates)
      if (d > 31 || m > 12) {
        d = 0;
        m = 0;
        y = 0;
      }

      if (d == 0 && m == 0 && y == 0) {
        return null;
      }
      else {
        if (displayValuesAreUtc) {
          return new Date(Date.UTC(y, m - 1, d));
        }
        else {
          return new Date(y, m - 1, d);
        }
      }
    }

    // Split and parse
    if (s.indexOf("/") != -1) {
      dp = s.split("/");
    }
    else {
      if (s.indexOf("-") != -1) {
        dp = s.split("-");
      }
      else {
        dp = s.split(" ");
      }
    }
    if (_config.dayMonthYearOrder == "DMY") {
      if (dp.length > 0) d = parseFloat(dp[0]);
      if (dp.length > 1) m = parseFloat(dp[1]);
      if (dp.length > 2) y = parseFloat(dp[2]);
    }
    else {
      if (dp.length > 0) m = parseFloat(dp[0]);
      if (dp.length > 1) d = parseFloat(dp[1]);
      if (dp.length > 2) y = parseFloat(dp[2]);
    }
    if (m === 0) m = new Date().getMonth() + 1;
    if (m > 12 && d < 13) {
      // Swap day and month
      temp = m;
      m = d;
      d = temp;
    }
    if (y === 0) {
      // Assume current year
      y = new Date().getFullYear();
    }
    if (y < 100) {
      // Year is only 2 digits
      if (historic) {
        var cy = parseFloat((new Date().getFullYear() + '').substr(2, 2));

        // Historic (past) date
        if (y < cy) {
          y += 2000;
        }
        else {
          y += 1900;
        }
      }
      else {
        y += 2000;
      }
    }
    if (y > 9999) y = 9999;
    try {
      if (isNaN(y) || isNaN(m) || isNaN(d)) {
        return null;
      }
      else {
        if (displayValuesAreUtc) {
          return new Date(Date.UTC(y, m - 1, d));
        }
        else {
          return new Date(y, m - 1, d);
        }
      }
    }
    catch (e) {
      return null;
    }
  }

  // ==============================================================================
  // PUBLIC: Parse a Time string into a Date object or null
  //
  // NOTE: The day, month and year portions of the returned value should be ignored
  // ==============================================================================
  function ParseTime(s, displayValuesAreUtc) {
    if (s) {
      var h = 0, m = 0, sec = 0;

      s = s.toUpperCase();
      var am = s.indexOf("A") !== -1;
      var pm = s.indexOf("P") !== -1;

      if (s === "NOW" || s === "TODAY") {
        // Format a time for parsing (so issues with UTC and parsing can all be sorted centrally, i.e., below
        s = FormatTime(new Date(), false, false);
      }

      // Split
      var tp = s.split(":");
      if (tp.length > 0) h = parseFloat(tp[0]);
      if (tp.length > 1) m = parseFloat(tp[1]);
      if (tp.length > 2) sec = parseFloat(tp[2]);

      if (pm && h < 12) {
        h += 12;
      }
      else if (am && h === 12) {
        h -= 12;
      }

      try {
        if (isNaN(h) || isNaN(m) || isNaN(sec)) {
          return null;
        }
        else {
          if (displayValuesAreUtc) {
            return new Date(Date.UTC(2000, 0, 1, h, m, sec));
          }
          else {
            return new Date(2000, 0, 1, h, m, sec);
          }
        }
      }
      catch (e) {
        return null;
      }
    }
    else {
      return null;
    }
  }

  // ==============================
  // PUBLIC: Parse a Currency value
  // ==============================
  function ParseCurrency(value) { 
    if (Runtime) {
      // finCC
      return Runtime.ParseNumber(value, -1);
    }
    else {
      return ParseNumberInternal("" + value, -1);
    }
  }

  // ============================
  // PUBLIC: Parse a Number value
  // ============================
  function ParseNumber(value, decimals) {
    if (Runtime) {
      // finCC
      return Runtime.ParseNumber(value, decimals);
    }
    else {
      return ParseNumberInternal("" + value, decimals);
    }
  }

  // ------------------------------------
  // PRIVATE: Parse a Number from a string
  // ------------------------------------
  function ParseNumberInternal(s, decimals) {
    if (decimals == -1) decimals = _config.currencyDecimals;

    // Remove Commas
    s += "";
    s = s.replace(/\,/g, "");

    // If using negative brackets then replace these
    if (s.startsWith("(") && s.endsWith(")")) {
      s = s.substr(1, s.length - 2);
      s = "-" + s;
    }

    // Remove invalid characters
    var s2 = s;
    s = "";
    var valid = "0123456789.-";
    for (var i = 0; i < s2.length; i++) {
      var c = s2.substr(i, 1);
      if (valid.indexOf(c) >= 0) {
        s += c;
      }
    }

    // Decimals
    var f = parseFloat(parseFloat(s).toFixed(decimals));

    if (f) return f; else return 0;
  }

  // ========================
  // PUBLIC: Theme properties
  // ========================
  function ThemeContrastColourBackground() {
    if (Runtime) {
      return Runtime.ThemeContrastColourBackground();
    }
    else {
      return _config.themeContrastColourBackground;
    }
  }
  function ThemeContrastColourForeground() {
    if (Runtime) {
      return Runtime.ThemeContrastColourForeground();
    }
    else {
      return _config.themeContrastColourForeground;
    }
  }
  function ThemeMainColourBackground() {
    if (Runtime) {
      return Runtime.ThemeMainColourBackground();
    }
    else {
      return _config.themeMainColourBackground;
    }
  }
  function ThemeMainColourForeground() {
    if (Runtime) {
      return Runtime.ThemeMainColourForeground();
    }
    else {
      return _config.themeMainColourForeground;
    }
  }

  // ======================
  // PUBLIC: Trim Functions
  // ======================
  function Trim(text) {
    return text.replace(/^\s+|\s+$/g, "");
  }
  function LTrim(text) {
    return text.replace(/^\s+/, "");
  }
  function RTrim(text) {
    return text.replace(/\s+$/, "");
  }

  // =================================================
  // PUBLIC: Insert spaces within a camel-cased String
  // =================================================
  function SplitWordsAtCapitals(s, upperCaseFirstLetter, splitAtNumbers) {
    var sb = "";

    // Initialise
    if (upperCaseFirstLetter === undefined) upperCaseFirstLetter = true;
    if (splitAtNumbers === undefined) splitAtNumbers = true;

    // Validate
    if (s) {
      s = RTrim(s);
    }
    else {
      return "";
    }

    // Parse
    var IgnoreNext = true;
    var LastChar = "";
    for (var i = 0; i < s.length; i++) {
      var c = s[i];

      switch (c) {
        case " ":
          // Ignore white space?
          IgnoreNext = true;
          break;

        default:
          if (splitAtNumbers && "0123456789".indexOf(c) != -1 && !"0123456789".indexOf(LastChar) == -1) {
            if (!IgnoreNext) sb += " ";
            IgnoreNext = true;
          }
          else if (c == c.toUpperCase()) {
            if (!IgnoreNext) sb += " ";
            IgnoreNext = true;
          }
          else {
            IgnoreNext = false;
          }
          break;
      }

      if (upperCaseFirstLetter) {
        upperCaseFirstLetter = false;
        sb += c.toUpperCase();
      }
      else {
        sb += c;
      }
    }

    return sb;
  }

  // ======================================
  // PUBLIC: Get an Array from a CSV String
  // ======================================
  function ArrayFromCsvString(sourceString) {
    var i, j, strTemp, InQuotes, arr = [];

    // Initialise
    sourceString = "" + sourceString;

    // Anything to convert?
    if (sourceString.length == 0) return [];

    // Parse List
    j = 0;
    for (i = 0; i < sourceString.length; i++) {
      switch (sourceString.substr(i, 1)) {
        case ",":
          if (!InQuotes) {
            // Add Item
            strTemp = sourceString.substr(j, i - j);

            // Remove Quotes
            if (strTemp.length > 2 && strTemp.charAt(0) == "\"" && strTemp.charAt(strTemp.length - 1) == "\"") { strTemp = strTemp.substr(1, strTemp.length - 2); }

            // Replace doubled-up Quotes
            strTemp = strTemp.replace(/\"\"/g, "\"");

            // Add
            arr.push(strTemp);

            // Update pointers
            j = i + 1;
          }
          break;

        case "\"":
          InQuotes = !InQuotes;
          break;
      }
    }

    // Add Final Item
    if (j <= sourceString.length) {
      strTemp = sourceString.substr(j);
      if (strTemp.length > 2 && strTemp.charAt(0) == "\"" && strTemp.charAt(strTemp.length - 1) == "\"") { strTemp = strTemp.substr(1, strTemp.length - 2); }
      strTemp = strTemp.replace(/\"\"/g, "\"");
      arr.push(strTemp);
    }
    else {
      // Final Item is a blank string
      if (sourceString.charAt(sourceString.length - 1) == ",") {
        arr.push("");
      }
    }

    return arr;
  }

  // =========================================
  // PUBLIC: Create a CSV string from an Array
  // =========================================
  function ArrayToCsvString(array) {
    var s = "";

    for (var i = 0; i < array.length; i++) {
      var item = array[i];

      if (s) s += ",";

      if (item.indexOf(",") != -1) {
        // Quote
        s += "\"" + item + "\"";
      }
      else {
        s += item;
      }
    }

    return s;
  }

  // =============================
  // PUBLIC: Minimise Widget Modal
  // =============================
  function Minimise() {
    // Use an existing notification method to achieve this
    widget.__requestForm("__minimise", {});
  }

  // ========================
  // PUBLIC: Version property
  // ========================
  function Version() {
    return "1.31";
  }


  // ====================================
  // Return PUBLIC methods and properties
  // ====================================
  var _self =
  {
    ArrayAllowLookupById: ArrayAllowLookupById,
    ArrayFromCsvString: ArrayFromCsvString,
    ArrayRemove: ArrayRemove,
    ArrayToCodeDescriptionList: ArrayToCodeDescriptionList,
    ArrayToCsvString: ArrayToCsvString,

    AccountTerminology: function (plural) { return _config.accountTerminology + (plural ? "s" : ""); },
    CompareDates: CompareDates,
    CurrencyDecimals: function () { return _config.currencyDecimals; },
    CurrencySymbol: function () { return _config.currencySymbol; },
    DateAddDays: DateAddDays,
    DayMonthYearOrder: function () { return _config.dayMonthYearOrder; },
    FormatCardExpiryDate: FormatCardExpiryDate,
    FormatCurrency: FormatCurrency,
    FormatDate: FormatDate,
    FormatDateForGrid: FormatDateForGrid,
    FormatDateTime: FormatDateTime,
    FormatTime: FormatTime,
    FormatUtcDate: FormatUtcDate,
    FormatUtcDateTime: FormatUtcDateTime,
    FormatNumber: FormatNumber,

    GetHostingContext: GetHostingContext,

    GetAgeInYears: GetAgeInYears,
    GetAgeText: GetAgeText,
    GetWeekDayName: GetWeekDayName,
    GetWeekDayNameFromDate: GetWeekDayNameFromDate,

    IsColourDark: IsColourDark,
    IsColourLight: IsColourLight,
    IsHighDpi: IsHighDpi,

    ParseCurrency: ParseCurrency,
    ParseDate: ParseDate,
    ParseNumber: ParseNumber,
    ParseTime: ParseTime,

    Round: Round,
    RoundCurrency: RoundCurrency,
    RoundCurrencyDown: RoundCurrencyDown,
    RoundCurrencyUp: RoundCurrencyUp,

    ThemeContrastColourBackground: ThemeContrastColourBackground,
    ThemeContrastColourForeground: ThemeContrastColourForeground,
    ThemeMainColourBackground: ThemeMainColourBackground,
    ThemeMainColourForeground: ThemeMainColourForeground,

    Trim: Trim,
    LTrim: LTrim,
    RTrim: RTrim,
    SplitWordsAtCapitals: SplitWordsAtCapitals,

    Minimise: Minimise,

    Version: Version,

    /* Compatibility */
    IsApp: function () { return mIsApp; },
    IsApp_Android: function () { return mIsApp_Android; },
    IsApp_iOS: function () { return mIsApp_iOS; },

    // Friend
    FormatDateInternal: FormatDateInternal,
    IsClientManagement: IsClientManagement,
  };

  return _self;
}();

console.log("  widget (generic)");


// ----------
// Poly-fills
// ----------

// Console
if (!window.console) console = { log: function () { }, warn: function () { } };
