/* Minification failed. Returning unminified contents.
(13,9-10): run-time warning JS1195: Expected expression: c
(14,96-97): run-time warning JS1004: Expected ';': {
(26,49-50): run-time warning JS1195: Expected expression: )
(26,52-53): run-time warning JS1195: Expected expression: >
(42,18-19): run-time warning JS1195: Expected expression: )
(49,18-19): run-time warning JS1195: Expected expression: )
(52,18-19): run-time warning JS1195: Expected expression: )
(72,31-32): run-time warning JS1004: Expected ';': {
(80,39-40): run-time warning JS1004: Expected ';': {
(83,33-34): run-time warning JS1004: Expected ';': {
(89,43-44): run-time warning JS1004: Expected ';': {
(141,25-26): run-time warning JS1004: Expected ';': {
(144,24-25): run-time warning JS1004: Expected ';': {
(147,24-25): run-time warning JS1004: Expected ';': {
(150,28-29): run-time warning JS1004: Expected ';': {
(153,29-30): run-time warning JS1004: Expected ';': {
(167,9-10): run-time warning JS1002: Syntax error: }
(171,9-10): run-time warning JS1002: Syntax error: }
(173,32-33): run-time warning JS1197: Too many errors. The file might not be a JavaScript file: {
(28,25-35): run-time warning JS1018: 'return' statement outside of function: return '';
(35,29-47): run-time warning JS1018: 'return' statement outside of function: return '1 result';
(38,29-65): run-time warning JS1018: 'return' statement outside of function: return unfilteredCount + ' results';
(41,21-189): run-time warning JS1018: 'return' statement outside of function: return 'Showing ' + firstVisibleIndex + ' - ' + (pageItemCount + Math.min(this.UnFilteredCount() - pageItemCount, this.ItemsPerPage)) + ' of ' + this.UnFilteredCount();
(45,25-34): run-time warning JS1018: 'return' statement outside of function: return 0;
(48,21-119): run-time warning JS1018: 'return' statement outside of function: return (((this.UnFilteredCount() - remainder) / this.ItemsPerPage) - 1) + (remainder > 0 ? 1 : 0);
(51,21-50): run-time warning JS1018: 'return' statement outside of function: return this.PageNumber() + 1;
(85,21-28): run-time warning JS1018: 'return' statement outside of function: return;
(165,17-29): run-time warning JS1018: 'return' statement outside of function: return true;
 */
//----------------------------------------------------
// Copyright 2021-2022 Epic Systems Corporation
//----------------------------------------------------
/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/knockout/knockout.d.ts" />
/// <reference path="typings/bootstrap/bootstrap.d.ts" />
/// <reference path="typings/knockout.mapping/knockout.mapping.d.ts" />
/// <reference path="Epic.Shell.ts" />
var Epic;
(function (Epic) {
    var AppOrchard;
    (function (AppOrchard) {
        class DelayedFilteredManager {
            constructor(filterDelay, filterMethod, filtersKO, itemsPerPage, initialPageNumber) {
                this.FilterDelay = 50;
                this.RefreshTimer = null;
                this.ItemsPerPage = 0;
                this.FilterHasRun = false;
                this.PageNumber = ko.observable(0);
                this.ObservableCollections = [];
                this.FilterObject = null;
                this.OnFilteredDelegate = [];
                this.UnFilteredCount = ko.observable(0);
                this.UnFilteredCountLessDuplicates = ko.observable(0); //only used if the objects we're filtering have an "Id" property
                this.FilteredCount = ko.observable(0);
                this.DisplayText = ko.computed(() => {
                    if (this.UnFilteredCount() == 0) {
                        return '';
                    }
                    var pageItemCount = (this.ItemsPerPage * (this.PageNumber()));
                    var firstVisibleIndex = pageItemCount + 1;
                    if (this.ItemsPerPage == 0) {
                        const unfilteredCount = this.UnFilteredCountLessDuplicates() != 0 ? this.UnFilteredCountLessDuplicates() : this.UnFilteredCount();
                        if (unfilteredCount == 1) {
                            return '1 result';
                        }
                        else {
                            return unfilteredCount + ' results';
                        }
                    }
                    return 'Showing ' + firstVisibleIndex + ' - ' + (pageItemCount + Math.min(this.UnFilteredCount() - pageItemCount, this.ItemsPerPage)) + ' of ' + this.UnFilteredCount();
                });
                this.TotalPages = ko.computed(() => {
                    if (!this.UnFilteredCount() || this.UnFilteredCount() == 0 || this.ItemsPerPage == 0) {
                        return 0;
                    }
                    var remainder = this.UnFilteredCount() % this.ItemsPerPage;
                    return (((this.UnFilteredCount() - remainder) / this.ItemsPerPage) - 1) + (remainder > 0 ? 1 : 0);
                });
                this.CurrentPage = ko.computed(() => {
                    return this.PageNumber() + 1;
                });
                if (filterDelay > 50) {
                    this.FilterDelay = filterDelay;
                }
                this.FilterMethod = filterMethod;
                this.FilterObject = filtersKO;
                if (itemsPerPage) {
                    this.ItemsPerPage = itemsPerPage;
                }
                //this.FilterObject.subscribe(this.InitiateFilter, this);
                for (var index in this.FilterObject()) {
                    var koProp = this.FilterObject()[index];
                    if (koProp != null && koProp.subscribe != null) {
                        koProp.subscribe(this.InitiateFilter, this);
                    }
                }
                if (initialPageNumber) {
                    this.PageNumber(initialPageNumber);
                }
            }
            ClearCollection() {
                if (this.RefreshTimer != null) {
                    window.clearTimeout(this.RefreshTimer);
                }
                if (this.ObservableCollections.length > 0) {
                    this.ObservableCollections.pop();
                }
            }
            AddCollection(collection) {
                this.ObservableCollections.push(collection);
            }
            InitiateFilter(val) {
                if (this.RefreshTimer != null) {
                    return;
                }
                this.RefreshTimer = window.setTimeout(this.ExecuteFilter, this.FilterDelay, this);
            }
            ExecuteFilter(me, pageChange) {
                me.RefreshTimer = null;
                var unFilteredCount = 0;
                var filteredCount = 0;
                var uniqueObjects = [];
                var anyItemChanged = false;
                var maxVisibleCount = (me.ItemsPerPage == 0) ? 1000000 : me.ItemsPerPage;
                var initialSelectedItemIndex = (pageChange == true) ? (this.PageNumber() * this.ItemsPerPage) + 1 : 1;
                var maxSelectedItemIndex = initialSelectedItemIndex + maxVisibleCount;
                for (var collectionIndex in me.ObservableCollections) {
                    var collection = me.ObservableCollections[collectionIndex];
                    var changed = false;
                    for (var index in collection()) {
                        var objKO = collection()[index]();
                        var isFiltered = me.FilterMethod(objKO, me.FilterObject());
                        if (!isFiltered)
                            unFilteredCount++;
                        if (isFiltered)
                            filteredCount++;
                        isFiltered = isFiltered || !((unFilteredCount < maxSelectedItemIndex) && (unFilteredCount >= initialSelectedItemIndex));
                        if (objKO.IsFiltered() != isFiltered || !me.FilterHasRun) {
                            objKO.IsFiltered(isFiltered);
                            changed = true;
                        }
                        var objId = objKO.Id;
                        if (objId && !isFiltered && uniqueObjects.indexOf(objId) == -1) {
                            uniqueObjects.push(objId);
                        }
                    }
                    if (changed) {
                        anyItemChanged = true;
                        collection.notifySubscribers();
                    }
                }
                me.FilterHasRun = true;
                me.FilteredCount(filteredCount);
                me.UnFilteredCount(unFilteredCount);
                me.UnFilteredCountLessDuplicates(uniqueObjects.length);
                if (anyItemChanged && !(pageChange == true)) {
                    me.PageNumber(0);
                }
                if (me.OnFilteredDelegate.length > 0) {
                    for (var i in me.OnFilteredDelegate) {
                        try {
                            me.OnFilteredDelegate[i].call(me);
                        }
                        catch (e) {
                            alert(e);
                        }
                    }
                }
            }
            MoveFirst() {
                this.MoveToPage(0);
            }
            MoveLast() {
                this.MoveToPage(this.TotalPages());
            }
            MoveNext() {
                this.MoveToPage(this.PageNumber() + 1);
            }
            MovePrevious() {
                this.MoveToPage(this.PageNumber() - 1);
            }
            MoveToPage(val) {
                var initialSelectedItemIndex = 0;
                var maxSelectedItemIndex = 0;
                var tempIndex = 0;
                if (val > this.TotalPages()) {
                    val = this.TotalPages();
                }
                if (val < 1) {
                    val = 0;
                }
                this.PageNumber(val);
                this.ExecuteFilter(this, true);
                return true;
            }
        }
        AppOrchard.DelayedFilteredManager = DelayedFilteredManager;
        /** The base result for MVC controllers */
        class WebServiceResult {
        }
        AppOrchard.WebServiceResult = WebServiceResult;
        class SelectableEnumKO {
            constructor(koProp, key, value) {
                this.key = null;
                this.value = null;
                this.DependentKOProp = null;
                this.IsSelected = ko.observable(false);
                this.key = key;
                this.value = value;
                this.DependentKOProp = koProp;
                koProp.subscribe(() => {
                    let selected = (this.DependentKOProp() == this.value);
                    this.IsSelected(selected);
                }, this);
                this.IsSelected((this.DependentKOProp() == this.value));
            }
        }
        AppOrchard.SelectableEnumKO = SelectableEnumKO;
        /** The different modes for sorting */
        (function (SortOrderMode) {
            SortOrderMode[SortOrderMode["Ascending"] = 0] = "Ascending";
            SortOrderMode[SortOrderMode["Descending"] = 1] = "Descending";
        })(AppOrchard.SortOrderMode || (AppOrchard.SortOrderMode = {}));
        var SortOrderMode = AppOrchard.SortOrderMode;
        /** The different supported HTTP methods for AJAX */
        (function (HttpMethod) {
            HttpMethod[HttpMethod["POST"] = 0] = "POST";
            HttpMethod[HttpMethod["GET"] = 1] = "GET";
        })(AppOrchard.HttpMethod || (AppOrchard.HttpMethod = {}));
        var HttpMethod = AppOrchard.HttpMethod;
        /** The type of MessageBox to show */
        (function (MessageBoxType) {
            MessageBoxType[MessageBoxType["Confirm"] = 0] = "Confirm";
            MessageBoxType[MessageBoxType["Show"] = 1] = "Show";
        })(AppOrchard.MessageBoxType || (AppOrchard.MessageBoxType = {}));
        var MessageBoxType = AppOrchard.MessageBoxType;
        /** The icon to include on the MessageBox */
        (function (MessageBoxIcon) {
            MessageBoxIcon[MessageBoxIcon["Error"] = 0] = "Error";
            MessageBoxIcon[MessageBoxIcon["Information"] = 1] = "Information";
            MessageBoxIcon[MessageBoxIcon["Question"] = 2] = "Question";
            MessageBoxIcon[MessageBoxIcon["Warning"] = 3] = "Warning";
        })(AppOrchard.MessageBoxIcon || (AppOrchard.MessageBoxIcon = {}));
        var MessageBoxIcon = AppOrchard.MessageBoxIcon;
        /** A Wrapper class for common Regular Expressions */
        class RegEx {
        }
        RegEx.Email = new RegExp("/^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i");
        AppOrchard.RegEx = RegEx;
        /** A Wrapper class for ultility methods */
        class Util {
            static IsNullOrEmpty(value) {
                return (!value || value.length == 0);
            }
            static IsNullOrWhitespace(value) {
                return (!value || value.trim().length == 0);
            }
            static ShowFadingMessage(selector, message, timeout = 5000, allowTabAccess = true) {
                if (selector == null || $(selector) == null)
                    return;
                $(selector).text(message);
                $(selector).attr('aria-label', message);
                if (allowTabAccess) {
                    $(selector).prop('tabindex', 0);
                }
                $(selector).removeClass("fade");
                $(selector).css({ "opacity": "1" });
                setTimeout(function () {
                    $(selector).prop('tabindex', -1);
                    $(selector).addClass("fade");
                    $(selector).css({ "opacity": "0" });
                }, timeout);
            }
            /**
             * Show a styled validation message.
             * @param selector JQuery Selector to find element(s) to attach the message to
             * @param message Message text to display
             * @param cssClass Css class to add to style the message (warning, informational, success). Default if none passed is to style as an error message.
             * @param showIcon Whether an icon should show before the message.
             * @param messageShouldFade Whether the message should fade after displaying (default is false).
             */
            static ShowValidationMessage(selector, message, cssClass, showIcon, messageShouldFade) {
                let availableCssClasses = ["success", "informational", "warning"];
                if (!Util.IsNullOrEmpty(cssClass) && availableCssClasses.indexOf(cssClass) === -1) {
                    cssClass = "";
                }
                let otherClasses = availableCssClasses.filter(other => other !== cssClass);
                const $selector = $(selector);
                // remove other validation classes in case the same element is being reused for different situations
                for (const otherClass of otherClasses) {
                    $selector.removeClass(otherClass);
                }
                $selector.addClass("validation-message-pill");
                if (!Util.IsNullOrEmpty(cssClass)) {
                    $selector.addClass(cssClass);
                }
                if (showIcon) {
                    $selector.addClass("validation-icon");
                }
                if (messageShouldFade) {
                    Epic.AppOrchard.Util.ShowFadingMessage(selector, message);
                }
                else {
                    $selector.text(message);
                    $selector.attr('aria-label', message);
                    $selector.prop('tabindex', 0);
                    $selector.removeClass("fade");
                    $selector.css({ "opacity": "1" });
                }
            }
            static HideMessage(selector) {
                const $selector = $(selector);
                $selector.prop('tabindex', -1);
                $selector.addClass("fade");
                $selector.css({ "opacity": "0" });
            }
            static ScrollToElement(selector) {
                $('html, body').animate({
                    scrollTop: $(selector).offset().top
                }, 700);
            }
            static Hide(selector) {
                $(selector).hide();
            }
            static enumToSelectArray(enumRef) {
                let result = [];
                for (var index in enumRef) {
                    var raw = index;
                    var asNum = +index;
                    if (!index ||
                        raw == asNum) {
                        continue;
                    }
                    var value = parseInt(enumRef[index]);
                    result.push(new AppOrchard.DbResources.SelectionType(value, this.GetEnumValueName(value, enumRef)));
                }
                return result;
            }
            /** Converts an enum into a KnockoutArray allowing databinding to Select fields */
            static enumToKoArray(enumRef, sourcePropKO) {
                var result = ko.observableArray([]);
                for (var index in enumRef) {
                    var raw = index;
                    var asNum = +index;
                    if (!index ||
                        raw == asNum) {
                        continue;
                    }
                    var value = parseInt(enumRef[index]);
                    result.push(ko.observable(new SelectableEnumKO(sourcePropKO, index, enumRef[index])));
                }
                result.extend((fnName) => {
                    if (fnName == 'GetEnumValueName') {
                        return Epic.AppOrchard.Util.GetEnumValueName;
                    }
                });
                return result;
            }
            static GetEnumValueName(value, enumValues) {
                return enumValues[value];
            }
            static EnumValueExists(value, enumValues) {
                return !this.IsNullOrWhitespace(this.GetEnumValueName(value, enumValues));
            }
            /** Adds the error/warning CSS to an element on the DOM, including the hover text.
             *  @param (string) elmId - The ID of the element
             *  @param (string) errorMessage - The error/warning message message. Default is to use the defaulterrormessage attribute.
             *  @param (boolean) isWarning - Whether the message is really a warning and not an error.
              */
            static AddErrorClassToElement(elmId = null, message = null, isWarning = false) {
                if (elmId) {
                    let elm = $("#" + elmId);
                    if (elm) {
                        if (!message) {
                            message = elm.attr("defaulterrormessage");
                        }
                        elm.attr("errormessage", message);
                        elm.attr("title", message);
                        if (!isWarning) {
                            elm.addClass("input-validation-error");
                        }
                        else {
                            elm.addClass("input-validation-warning");
                        }
                    }
                }
            }
            /** Removes the warning/error CSS class from the DOM element
             * @param (string) elmId - The DOM element id
             * @param (JQueryEventObject) event - The event of a form field
             */
            static RemoveErrorClassFromElement(elmId = null, event = null) {
                if (!elmId && event && event.target) {
                    elmId = event.target.id;
                }
                if (elmId) {
                    let elm = $("#" + elmId);
                    if (elm) {
                        let attrval = elm.attr("applyerrorclass");
                        if (attrval === "false") {
                            return;
                        }
                        elm.removeClass("input-validation-error");
                        elm.removeClass("input-validation-warning");
                        elm.attr("title", "");
                        elm.attr("errormessage", "");
                    }
                }
            }
            static TextAreaFocus(a, b) {
                var r = b.currentTarget.getAttribute("rows-on-focus");
                if (r) {
                    $("#" + b.currentTarget.id).attr("rows", r);
                }
            }
            static TextAreaBlur(a, b) {
                var r = b.currentTarget.getAttribute("rows-on-blur");
                if (r) {
                    $("#" + b.currentTarget.id).attr("rows", r);
                }
            }
            /** Get the base URL for this web site */
            static GetBaseUrl() {
                return window.location.protocol + "//" + window.location.hostname + (window.location.port && ":" + window.location.port) + (window.location.port == "44305" ? "/VendorServices" : "") + "/";
            }
            /** Get the full URL for a relative path
             * @param (string) path - The relative path to the resource action
             */
            static GetFullUrl(path) {
                let baseUrl = Epic.AppOrchard.Util.GetBaseUrl();
                let index = path.indexOf(baseUrl);
                if (index !== -1) {
                    path = path.substring(index, path.length);
                }
                if (baseUrl.slice(baseUrl.length - 1) !== "/") {
                    if (path.slice(0, 1) !== "/") {
                        path = "/" + path;
                    }
                }
                else {
                    if (path.slice(0, 1) === "/") {
                        path = path.substring(1);
                    }
                }
                return baseUrl + path;
            }
            /** Get the full URL for the name of a specific image file.
             * @param (string) imageFileName - The name of an image file
             */
            static GetFullImagePath(imageFileName) {
                return Epic.AppOrchard.Util.GetBaseUrl() + "Content/Images/" + imageFileName;
            }
            static LogJSEvent(success, status, errorMsg, ajaxUrl) {
                var form = $('#errorForm');
                var token = $('input[name="__RequestVerificationToken"]', form).val();
                var errorModel = { success: success, status: status, errorMsg: errorMsg, ajaxUrl: ajaxUrl };
                try {
                    var settings = {};
                    settings.url = Epic.AppOrchard.Util.GetFullUrl("/Error/LogJSEvent");
                    settings.type = "POST";
                    settings.async = true;
                    settings.timeout = 2000;
                    settings.data = { __RequestVerificationToken: token, errorModel: errorModel };
                    $.ajax(settings);
                }
                catch (ex) {
                    ex = null;
                }
            }
            static NumberInputHelper(event, allowDecimal) {
                if (event.type == "keydown") {
                    if (event.key == "E" || event.key == "e" || (!allowDecimal && event.key == ".")) {
                        event.preventDefault();
                        event.stopPropagation();
                        event.stopImmediatePropagation();
                    }
                }
                return;
            }
            static RaiseClickEventOnEnter(event, raiseOnSpace = false, preventBubble = false) {
                if (event.keyCode === 13 ||
                    (raiseOnSpace && event.keyCode === 32)) {
                    $(event.srcElement).click();
                    if (preventBubble) {
                        event.preventDefault();
                        event.stopPropagation();
                    }
                }
                return;
            }
            static FormatNumber(num, enforceZeroOrTwoDecimals = false, enforceTwoDecimals = false) {
                if (num) {
                    let str = num.toString();
                    let intPart;
                    let decimalPart = "";
                    if (str.indexOf(".") > -1) {
                        let parts = str.split(".");
                        intPart = parts[0];
                        decimalPart = "." + parts[1] + ((enforceZeroOrTwoDecimals && parts[1].length == 1) ? "0" : "");
                    }
                    else {
                        intPart = str;
                    }
                    if (enforceTwoDecimals) {
                        if (decimalPart.length == 0)
                            decimalPart = ".00";
                        else if (decimalPart.length == 2)
                            decimalPart += "0";
                        else if (decimalPart.length > 3)
                            decimalPart = decimalPart.substring(0, 3);
                    }
                    return intPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") + decimalPart;
                }
                return "0";
            }
            static FormatDollarNumber(num, enforceZeroOrTwoDecimals = false) {
                return "$" + this.FormatNumber(num, enforceZeroOrTwoDecimals);
            }
            static IsStrictUrlAllowlistInvalid(element) {
                var regex = /^([\-\.%:_/0-9a-zA-Z]+)$/;
                var text = element.val() + "";
                var matches = text.match(regex);
                if (matches == null)
                    return true;
                return false;
            }
            static IsProtocolMissing(element) {
                var regex = /^(https:\/\/)|(http:\/\/)/;
                var text = element.val() + "";
                if (regex.test(text)) {
                    return false;
                }
                return true;
            }
            static IsUrlTextAllowedCharacters(text) {
                var regex = /^([\_\-0-9a-zA-Z.()%]*)$/;
                var matches = text.match(regex);
                if (matches == null)
                    return false;
                return true;
            }
            static SiteDisplayName() {
                return $("#SiteDisplayName").text();
            }
            static ProgramDetailsDisplayName() {
                return $("#ProgramDetailsDisplayName").text();
            }
            static CustomerAgreementName() {
                return $("#CustomerAgreementName").text();
            }
            static IsAdmin() {
                return $("#IsAdmin").html() == "True";
            }
            static IsSuperAdmin() {
                return $("#IsSuperAdmin").html() == "True";
            }
            static HasUserAccountType() {
                return $("#HasUserAccountType").html() == "True";
            }
            /**
             * Converts a C# boolean value (from a string) to a JavaScript boolean.
             * If the input is neither "True" nor "False", returns undefined.
             * @param csVal
             */
            static CsToJsBoolean(csVal) {
                return csVal === "True" ? true : (csVal === "False" ? false : undefined);
            }
            static Username() {
                var name = $("#Username").html();
                if (name)
                    return name;
                return "";
            }
            static UserId() {
                var id = parseInt($("#UserId").html());
                if (id && !isNaN(id))
                    return id;
                return 0;
            }
            static IsUserLoggedIn() {
                return $("#UserId").length > 0;
            }
            static ShowSOJ() {
                $("#SOJ").show();
            }
            static HideSOJ() {
                $("#SOJ").hide();
            }
            static ShowLoadingGIF() {
                $("#LoadingGIF").show();
            }
            static HideLoadingGIF() {
                $("#LoadingGIF").hide();
            }
            static ShowLogoutWarning() {
                $("#LogoutWarningDialogue").show();
            }
            static HideLogoutWarning() {
                $("#LogoutWarningDialogue").hide();
            }
            static IsLogoutWarning() {
                return $("#LogoutWarningDialogue").is(":visible");
            }
            /**
             * Removes trailing blank lines caused by paragraphs or break elements from an element.
             * @param elem either DOM element or jQuery instance
             */
            static RemoveTrailingBlankLines(elem) {
                var jqueryElem = elem instanceof jQuery ? elem : $(elem);
                var childNodes = jqueryElem.contents();
                if (!childNodes || childNodes.length == 0) {
                    return;
                }
                var lastChild = childNodes[childNodes.length - 1];
                // check if last child is a paragraph (IE) and replace that with its contents
                if ($(lastChild).is("p")) {
                    var lastChildText = $(lastChild).text();
                    $(lastChild).replaceWith(lastChildText);
                }
                else if ($(lastChild).is("br")) {
                    $(lastChild).remove();
                    Util.RemoveTrailingBlankLines(jqueryElem);
                }
                return;
            }
            /**
             * Updates hyperlinks inside an element so they will open in a new tab
             * @param elem
             */
            static SetLinksToOpenInNewTab(elem) {
                $(elem).find("a").each(function () { $(this).attr("target", "_blank"); }).end();
            }
            static Alert(title, body, focusOnClose, allowHtml) {
                var element = $("#modal_GenericAlert");
                var titleElement = element.find(".modal-title");
                var bodyElement = element.find(".modal-body");
                titleElement.text(title);
                if (typeof body === "string") {
                    if (allowHtml === true) {
                        bodyElement.html(body);
                    }
                    else {
                        bodyElement.text(body);
                    }
                }
                else {
                    bodyElement.empty();
                    bodyElement.append(body);
                }
                element.modal();
                element.on('hidden.bs.modal', function () {
                    if (focusOnClose) {
                        focusOnClose.focus({ preventScroll: true });
                    }
                });
            }
            static Confirm(title, body, onConfirm, onConfirmContext, onClose, onCloseContext, focusOnClose, allowHtml, warning, ...onConfirmArgArray) {
                var element = $("#modal_GenericConfirm");
                var titleElement = element.find(".modal-title");
                var bodyElement = element.find(".modal-body");
                var confirmButton = element.find("#GenericConfirmButton");
                var cancelButton = element.find("#GenericConfirmCancel");
                if (allowHtml === true) {
                    bodyElement.html(body);
                    titleElement.html(title);
                }
                else {
                    bodyElement.text(body);
                    titleElement.text(title);
                }
                if (warning === true) {
                    confirmButton.addClass("btn-danger");
                    confirmButton.removeClass("btn-primary");
                }
                else {
                    confirmButton.addClass("btn-primary");
                    confirmButton.removeClass("btn-danger");
                }
                //open up the modal
                element.modal();
                //get rid of any existing click handlers
                confirmButton.off("click");
                cancelButton.off("click");
                element.off("hidden.bs.modal");
                let confirmTriggered = false;
                //set a new click handler (the only one we want)
                confirmButton.click(function () {
                    if (confirmTriggered)
                        return;
                    confirmTriggered = true;
                    element.modal("hide");
                    onConfirm.apply(onConfirmContext, onConfirmArgArray);
                });
                cancelButton.click(function () {
                    if (onClose) {
                        onClose.apply(onCloseContext);
                    }
                    element.modal("hide");
                });
                //when the modal is closed, set focus
                element.on('hidden.bs.modal', function () {
                    if (focusOnClose) {
                        focusOnClose.focus({ preventScroll: true });
                    }
                    if (!confirmTriggered && onClose)
                        onClose.apply(onCloseContext);
                });
            }
            static FocusCollectFieldsFirstField() {
                $(Util.CollectFieldsSelector).find("#GenericCollectField0").get(0).focus();
            }
            static CollectFields(options) {
                let element = $(Util.CollectFieldsSelector);
                let titleElement = element.find(".modal-title");
                let bodyElement = element.find(".modal-body");
                let formElement = element.find(".modal-form");
                let submitButton = element.find("#GenericCollectFieldButton");
                let cancelButton = element.find("#GenericCollectFieldCancel");
                if (options.ModalTop) {
                    element.find("div").css("top", options.ModalTop);
                }
                else {
                    element.find("div").css("top", "");
                }
                if (options.UseDrawerStyle) {
                    element.addClass("modal-as-drawer");
                }
                else {
                    element.removeClass("modal-as-drawer");
                }
                titleElement.text(options.Title);
                let fieldElements = [];
                bodyElement.empty();
                if (!Epic.AppOrchard.Util.IsNullOrEmpty(options.HelpText)) {
                    if (options.AllowHtml === true) {
                        let helptextElement = $(options.HelpText);
                        bodyElement.append(helptextElement);
                    }
                    else {
                        let helptextElement = $("<p></p>");
                        helptextElement.text(options.HelpText);
                        bodyElement.append(helptextElement);
                    }
                }
                if (options.Warning === true) {
                    submitButton.addClass("btn-danger");
                    submitButton.removeClass("btn-primary");
                }
                else {
                    submitButton.addClass("btn-primary");
                    submitButton.removeClass("btn-danger");
                }
                if (options.SubmitButtonLabel) {
                    submitButton.text(options.SubmitButtonLabel);
                }
                else {
                    submitButton.text("Submit");
                }
                for (let fieldIndex = 0; fieldIndex < options.Fields.length; fieldIndex++) {
                    let currentField = options.Fields[fieldIndex];
                    let fieldName = "GenericCollectField" + fieldIndex;
                    let wrapperElement = $("<label></label>");
                    wrapperElement.prop("for", fieldName);
                    let spanElement = $("<span class='modal-label'></span>");
                    let helptextElement = currentField.GetHelptextElement(fieldIndex > 0 && fieldIndex == options.Fields.length - 1);
                    let fieldElement = currentField.GetInputElement(fieldName);
                    fieldElements.push(fieldElement);
                    if (currentField.Type === FieldType.PassThroughValue) {
                        wrapperElement.addClass("hidden");
                    }
                    if (currentField.IsRequired) {
                        spanElement.addClass("required-field-span");
                    }
                    spanElement.text(currentField.Label);
                    if (currentField.Props) {
                        for (let propIndex = 0; propIndex < currentField.Props.length; propIndex++) {
                            fieldElement.prop(currentField.Props[propIndex].Key, currentField.Props[propIndex].Value);
                        }
                    }
                    if (currentField.StartingValue) {
                        switch (currentField.Type) {
                            case Epic.AppOrchard.FieldType.Date:
                                let asDate = new Date(currentField.StartingValue);
                                let asDateJson = asDate.toJSON();
                                fieldElement.val(asDateJson.substr(0, asDateJson.indexOf("T")));
                                break;
                            case Epic.AppOrchard.FieldType.MultiSelect:
                                let keys = currentField.StartingValue.split(";");
                                for (let keyIndex = 0; keyIndex < keys.length; keyIndex++) {
                                    fieldElement.find("input[type='checkbox'][value='" + keys[keyIndex] + "'").prop("checked", true);
                                }
                                break;
                            case Epic.AppOrchard.FieldType.Switch:
                                fieldElement.prop("checked", currentField.StartingValue === "true");
                                break;
                            default:
                                fieldElement.val(currentField.StartingValue);
                                break;
                        }
                    }
                    else {
                        fieldElement.val("");
                    }
                    if (currentField.Type == Epic.AppOrchard.FieldType.Url) {
                        fieldElement.on("change", currentField.GetOnChangeFunction());
                        fieldElement.on("keyup", currentField.GetOnChangeFunction());
                    }
                    //we can't do this until fieldElement has its data populated, otherwise the initial state will always show 0 characters in the field
                    let characterCounterElement = currentField.GetCharacterCounterElement(fieldName);
                    wrapperElement.append(spanElement);
                    wrapperElement.append("&nbsp;");
                    if (helptextElement) {
                        wrapperElement.append(helptextElement);
                        wrapperElement.append("&nbsp;");
                    }
                    wrapperElement.append(fieldElement);
                    if (characterCounterElement) {
                        wrapperElement.append(characterCounterElement);
                    }
                    bodyElement.append(wrapperElement);
                }
                element.on("shown.bs.modal", function () {
                    //we scroll to the top when the modal is closed with the submit or cancel button, but if it gets close some other way, we'll scroll to the top when it opens
                    bodyElement.scrollTop(0);
                    fieldElements[0].focus();
                    Epic.AppOrchard.Util.CleanKONode($("#GenericCollectFieldBody")[0]);
                    if (options.KnockoutModel) {
                        Epic.AppOrchard.PageLoad.BindKnockoutModelToUI("GenericCollectFieldBody", options.KnockoutModel);
                    }
                });
                //define the options to use for the modal, first setup defaults
                let modalOptions = {
                    backdrop: true,
                    keyboard: true,
                    show: true,
                };
                //and then override if this specific CollectFields call instance wants to override
                if (options.ModalOptions !== undefined) {
                    if (options.ModalOptions.backdrop !== undefined) {
                        modalOptions.backdrop = options.ModalOptions.backdrop;
                    }
                    if (options.ModalOptions.keyboard !== undefined) {
                        modalOptions.keyboard = options.ModalOptions.keyboard;
                    }
                    if (options.ModalOptions.show !== undefined) {
                        modalOptions.show = options.ModalOptions.show;
                    }
                }
                //open up the modal
                element.modal(modalOptions);
                element.addClass("collect-open");
                //define the submit function
                let submitFunction = function (event) {
                    if (event.type == "submit") {
                        event.preventDefault();
                    }
                    //scroll the body element back to initial state, that way the next time it opens it's not scrolled down at all
                    bodyElement.scrollTop(0);
                    if (submitTriggered && !options.RequireManualClose)
                        return;
                    submitTriggered = true;
                    let submitArray = [];
                    for (let fieldElementIndex = 0; fieldElementIndex < fieldElements.length; fieldElementIndex++) {
                        let field = fieldElements[fieldElementIndex];
                        if (field.is("span.collect-field-multiselect")) {
                            let selectedCheckboxValues = [];
                            field.find("input[type='checkbox']:checked").each((_, element) => { selectedCheckboxValues.push("" + element.value); });
                            submitArray.push(selectedCheckboxValues);
                        }
                        else if (field.is("input[type='email']") || field.is("input[type='url']")) {
                            let htmlField = field[0];
                            if (!htmlField.validity.valid) {
                                return;
                            }
                            submitArray.push(fieldElements[fieldElementIndex].val());
                        }
                        else if (field.is("div.collect-field-category")) {
                            if (options.KnockoutModel) {
                                submitArray.push(options.KnockoutModel.SelectedCategoryIds());
                            }
                            else {
                                submitArray.push([]);
                            }
                        }
                        else if (field.is("div.collect-field-primary-category")) {
                            if (options.KnockoutModel) {
                                submitArray.push(options.KnockoutModel.PrimaryCategory_Id());
                            }
                            else {
                                submitArray.push(0);
                            }
                        }
                        else if (field.is("input.collect-field-switch")) {
                            let htmlField = field[0];
                            submitArray.push(htmlField.checked);
                        }
                        else {
                            submitArray.push(fieldElements[fieldElementIndex].val());
                        }
                    }
                    if (options.OnSubmitAdditionalArguments) {
                        submitArray = submitArray.concat(options.OnSubmitAdditionalArguments);
                    }
                    options.OnSubmit.apply(options.OnSubmitContext, submitArray);
                    if (!options.RequireManualClose) {
                        element.modal("hide");
                    }
                };
                //get rid of any existing event handlers
                formElement.off("submit");
                submitButton.off("click");
                cancelButton.off("click");
                element.off("hidden.bs.modal");
                let submitTriggered = false;
                //set a new submit handler (the only one we want)
                formElement.on("submit", submitFunction);
                //set a new click handler (the only one we want)
                submitButton.click(submitFunction);
                cancelButton.click(function () {
                    //scroll the body element back to initial state, that way the next time it opens it's not scrolled down at all
                    bodyElement.scrollTop(0);
                    if (options.OnClose) {
                        options.OnClose.apply(options.OnCloseContext);
                    }
                    element.modal("hide");
                });
                //when the modal is closed, set focus
                element.on('hidden.bs.modal', function () {
                    element.removeClass("collect-open");
                    if (options.FocusOnClose) {
                        options.FocusOnClose.focus({ preventScroll: true });
                    }
                    //clear out bootstrap's data about the modal
                    element.data('bs.modal', null);
                });
            }
            static CloseCollectFieldsModal() {
                let element = $(Util.CollectFieldsSelector);
                element.modal("hide");
            }
            static CookieExists(name) {
                for (var cookiePair of document.cookie.split(";")) {
                    var cookie = cookiePair.split("=");
                    if (name == cookie[0].trim()) {
                        return true;
                    }
                }
                return false;
            }
            static GetCookieValue(name) {
                for (var cookiePair of document.cookie.split(";")) {
                    var cookie = cookiePair.split("=");
                    if (name == cookie[0].trim()) {
                        return cookie[1].trim();
                    }
                }
                return null;
            }
            static CreateCookie(name, value, expiryDate, domain) {
                var newCookie = name + '=' + value + '; expires=' + expiryDate + '; path=/';
                if (domain && domain.length > 0) {
                    newCookie += '; domain=' + domain + '; SameSite=None; Secure=true';
                }
                document.cookie = newCookie;
            }
            static UseGACookies() {
                var useCookies = false;
                if (Epic.AppOrchard.Util.GetCookieValue(Epic.AppOrchard.Util.GACookieName) == "true") {
                    useCookies = true;
                }
                return useCookies;
            }
            static MatchParentWidth(selector) {
                let elements = $(selector);
                elements.width(elements.parent().width());
            }
            static MatchParentHeight(selector, onWindowResize, offset) {
                //do it once to set initial size
                let elements = $(selector);
                offset = offset || 0;
                elements.height(elements.parent().height() + offset);
                if (onWindowResize) {
                    //then add an event listener in case the parent resizes
                    window.addEventListener('resize', function () {
                        elements.height(elements.parent().height() + offset);
                    });
                }
                else {
                    //then add an event listener in case the parent resizes
                    elements[0].addEventListener('resize', function () {
                        elements.height(elements.parent().height() + offset);
                    });
                }
            }
            static SetHeightBetweenElements(selector, elementsAbove, elementsBelow) {
                if (!selector || !elementsAbove || !elementsBelow) {
                    return;
                }
                let targetElement = $(selector);
                if (!targetElement) {
                    return;
                }
                let targetTop = targetElement.offset().top;
                let heightAbove = 0;
                for (let i = 0; i < elementsAbove.length; i++) {
                    let elementAbove = $(elementsAbove[i]);
                    let marginAboveTop = 0;
                    let marginAboveBottom = 0;
                    let elementAboveHeight = 0;
                    if (elementAbove) {
                        marginAboveTop = parseInt(elementAbove.css('marginTop').replace("px", ""));
                        marginAboveBottom = parseInt(elementAbove.css('marginBottom').replace("px", ""));
                        elementAboveHeight = elementAbove.height();
                    }
                    heightAbove = heightAbove + elementAboveHeight + marginAboveBottom + marginAboveTop;
                }
                if (!elementsBelow.length || elementsBelow.length < 0) {
                    return;
                }
                let highestElementBelow = $(elementsBelow[0]).offset().top;
                for (let i = 1; i < elementsBelow.length; i++) {
                    let elementBelow = $(elementsBelow[i]);
                    if (elementBelow) {
                        let elementBelowLoc = elementBelow.offset().top;
                        if (elementBelowLoc < highestElementBelow) {
                            highestElementBelow = elementBelowLoc;
                        }
                    }
                }
                let windowFitHeight = window.innerHeight - heightAbove;
                let distanceToNextElemBeneath = highestElementBelow - targetTop;
                let newHeight = Math.min(windowFitHeight, distanceToNextElemBeneath);
                if (newHeight >= 0) {
                    targetElement.height(newHeight);
                }
            }
            static CopyHeight(selectorForHeightSource, selectorForHeightDestination, includeMargin = false) {
                let source = $(selectorForHeightSource);
                let destination = $(selectorForHeightDestination);
                if (source && source.length == 1 && destination && destination.length > 0) {
                    if (includeMargin) {
                        destination.height(source.outerHeight(true));
                    }
                    else {
                        destination.height(source.height());
                    }
                }
            }
            static ResetHeight(selector) {
                let element = $(selector);
                if (element && element.length > 0) {
                    element.height("");
                }
            }
            static ParamToNumber(param) {
                return parseInt(param) || 0;
            }
            static ParamToNumberList(param) {
                if (!param)
                    return null;
                let stringValues = param.split(",");
                let intValues = [];
                for (let i = 0; i < stringValues.length; i++) {
                    if (Epic.AppOrchard.Util.IsNullOrEmpty(stringValues[i]))
                        continue;
                    let parsedValue = parseInt(stringValues[i]);
                    if (parsedValue && parsedValue > 0)
                        intValues.push(parsedValue);
                }
                return intValues.length > 0 ? intValues : null;
            }
            static IsInternetExplorer() {
                return !!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g);
            }
            static ShowIESupportWarningIfNeeded() {
                if (!Util.IsInternetExplorer() || Util.CookieExists(Util.IEWarningCookie)) {
                    return;
                }
                // Display the message about ending IE support
                $("#IEStopSupportWarning").show();
                $("#IESupportedWarningBodyPadding").show();
            }
            static SetIeWarningSnoozeCookie() {
                $("#IESupportedWarningBodyPadding").hide();
                // Set the cookie to expire in 1 day
                var expiryDate = new Date();
                expiryDate.setDate((new Date()).getDate() + 1);
                Util.CreateCookie(Util.IEWarningCookie, 'true', expiryDate.toUTCString());
            }
            static ShowCopyLaunchUrlModal(launchUrl, onClose, onCloseContext) {
                // populate launch URL and select whenever the textarea is focused to make copying easier
                var launchUrlInput = $("#modal_LaunchUrl #LaunchUrl");
                launchUrlInput.text(launchUrl).focus(function () { launchUrlInput.select(); });
                $("#modal_LaunchUrl #CopyLaunchUrlToClipboard").on('click', function () {
                    launchUrlInput.focus();
                    document.execCommand('copy');
                });
                if (onClose) {
                    $("#modal_LaunchUrl").on('hidden.bs.modal', function () { onClose.apply(onCloseContext); });
                }
                $("#modal_LaunchUrl").on('shown.bs.modal', function () { launchUrlInput.focus(); }).modal();
            }
            static GetDefaultColorBackground(value) {
                if (Epic.AppOrchard.DbResources && Epic.AppOrchard.DbResources.AppBackgroundColors) {
                    const colors = Epic.AppOrchard.DbResources.AppBackgroundColors;
                    return colors[value % colors.length];
                }
                else {
                    return "#6d55a3";
                }
            }
            /**
             * Unbinds a knockout node. This allows a new binding to be established on the node.
             * @param node
             */
            static CleanKONode(node) {
                //This function is needed because we use knockout and jquery. When knockout detects jquery is present, it uses jquery
                //to "clean" the node. In forms that have non-knockout event handlers this will delete those event handlers.
                //We don't want that to happen so...
                //get knockout's jquery disposal method and save it in a variable
                var koDisposalFunction = ko.utils.domNodeDisposal['cleanExternalData'];
                //clear out the jquery disposal method
                ko.utils.domNodeDisposal['cleanExternalData'] = function () { };
                //call knockout's cleanNode (which, sicne we cleared out the jquery disposal method, will use knockout's normal, non-destructive process)
                ko.cleanNode(node);
                //and then restore the jquery disposal method so any knockout-initiated cleaning can use the jquery version
                ko.utils.domNodeDisposal['cleanExternalData'] = koDisposalFunction;
            }
        }
        Util.GACookieName = "AOCookieForGA";
        Util.CollectFieldsSelector = "#modal_GenericCollectField";
        // indicates the user has seen and snoozed the IE warning
        Util.IEWarningCookie = "AO_IEWarning";
        AppOrchard.Util = Util;
        class API {
            static ExecuteAjaxUpload(url, toUpload, successFunction = function (data, textStatus, jqXHR) { }, errorFunction = function (jqXHR, textStatus, errorThrown) { }, thisContext = null) {
                if (url.toLowerCase().indexOf("http") !== 0) {
                    url = Epic.AppOrchard.Util.GetFullUrl(url);
                }
                var settings = {};
                settings.url = url;
                settings.type = "POST";
                settings.data = toUpload;
                settings.processData = false;
                settings.contentType = false;
                settings.success = function (data, textStatus, jqXHR) {
                    // ensure session is still active
                    if (Epic.AppOrchard.Shell.ForceLogoutOrRefreshSession(data, settings)) {
                        return;
                    }
                    if (successFunction) {
                        if (data) {
                            if (data.Success === true) {
                                try {
                                    if (thisContext) {
                                        successFunction.apply(thisContext, [data.Data, textStatus, jqXHR]);
                                    }
                                    else {
                                        successFunction(data.Data, textStatus, jqXHR);
                                    }
                                }
                                catch (ex) {
                                    //jqXHR.status = -1 * jqXHR.status;
                                    if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Title)) {
                                        data.Title = "Failure - without Title";
                                    }
                                    if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Message)) {
                                        data.Message = "Failure - without message";
                                    }
                                    if (ex) {
                                        data.Message += "\r\n[ Error caught: " + ex + "]";
                                    }
                                    settings.error(jqXHR, data.Title, data.Message);
                                }
                            }
                            else if (!data.Success) {
                                if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Title)) {
                                    data.Title = "Failure - without Title";
                                }
                                if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Message)) {
                                    data.Message = "Failure - without message";
                                }
                                settings.error(jqXHR, data.Title, data.Message);
                            }
                        }
                    }
                };
                settings.error = function (jqXHR, textStatus, errorThrown) {
                    if (errorFunction) {
                        try {
                            errorFunction(jqXHR, textStatus, errorThrown);
                        }
                        catch (ex) {
                            Epic.AppOrchard.Util.LogJSEvent(false, "Error function leaked error: " + ex);
                        }
                    }
                    else {
                        Epic.AppOrchard.Util.LogJSEvent(false, jqXHR.status + " - " + jqXHR.statusText, "Error occurred for an unhandled API call to url: ", url);
                    }
                };
                return $.ajax(settings);
            }
            /** Executes an ajax query sync/async and provides the option to provide success/error hooks
             * @param (Epic.AppOrchard.HttpMethod) httpMethod - The HTTP method
             * @param (string) url - The relative URL
             * @param (boolean) executeAsync - Whether to execute sync/async
             * @param (any) data - the request object that will be converted to JSON
             * @param (function (data: any, textStatus: string, jqXHR: JQueryXHR)) successFunction - The code to execute on success
             * @param (function (jqXHR: JQueryXHR, textStatus: string, errorThrown: string)) errorFunction - The code to execute on error
             * @param (number) timeout - the number of ms before timing out the request
             */
            static ExecuteAjax(httpMethod, url, executeAsync = true, dataIn = null, successFunction = function (data, textStatus, jqXHR) { }, errorFunction = function (jqXHR, textStatus, errorThrown) { }, timeout = 30000, isRawData = false, thisContext = null, background = false) {
                var httpMethodString;
                switch (httpMethod) {
                    case Epic.AppOrchard.HttpMethod.POST:
                        httpMethodString = "POST";
                        break;
                    case Epic.AppOrchard.HttpMethod.GET:
                        httpMethodString = "GET";
                        break;
                }
                if (url.toLowerCase().indexOf("http") !== 0) {
                    url = Epic.AppOrchard.Util.GetFullUrl(url);
                }
                var data = dataIn;
                if (dataIn != null && !isRawData) {
                    data = JSON.stringify(data);
                }
                if (!background) {
                    // reset the timer since the user is executing an action
                    Epic.AppOrchard.Shell.ResetLogoutTimer();
                }
                var settings = {};
                if (!isRawData) {
                    settings.dataType = "json";
                    settings.contentType = "application/json; charset=utf-8";
                }
                if (thisContext) {
                    settings.xhrFields = { rawIn: thisContext };
                }
                settings.url = url;
                settings.data = data;
                settings.type = httpMethodString;
                settings.success = function (data, textStatus, jqXHR) {
                    // ensure session is still active
                    if (Epic.AppOrchard.Shell.ForceLogoutOrRefreshSession(data, settings)) {
                        return;
                    }
                    if (successFunction) {
                        if (data) {
                            if (data.Success === true) {
                                try {
                                    if (thisContext) {
                                        successFunction.apply(thisContext, [data.Data, textStatus, jqXHR]);
                                    }
                                    else {
                                        successFunction(data.Data, textStatus, jqXHR);
                                    }
                                }
                                catch (ex) {
                                    //jqXHR.status = -1 * jqXHR.status;
                                    if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Title)) {
                                        data.Title = "Failure - without Title";
                                    }
                                    if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Message)) {
                                        data.Message = "Failure - without message";
                                    }
                                    if (ex) {
                                        data.Message += "\r\n[ Error caught: " + ex + "]";
                                    }
                                    settings.error(jqXHR, data.Title, data.Message);
                                }
                            }
                            else if (!data.Success) {
                                if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Title)) {
                                    data.Title = "Failure - without Title";
                                }
                                if (Epic.AppOrchard.Util.IsNullOrEmpty(data.Message)) {
                                    data.Message = "Failure - without message";
                                }
                                settings.error(jqXHR, data.Title, data.Message);
                            }
                        }
                    }
                };
                settings.error = function (jqXHR, textStatus, errorThrown) {
                    if (errorFunction) {
                        try {
                            errorFunction(jqXHR, textStatus, errorThrown);
                        }
                        catch (ex) {
                            Epic.AppOrchard.Util.LogJSEvent(false, "Error function leaked error: " + ex);
                        }
                    }
                    else {
                        Epic.AppOrchard.Util.LogJSEvent(false, jqXHR.status + " - " + jqXHR.statusText, "Error occurred for an unhandled API call to url: ", url);
                    }
                };
                settings.async = executeAsync;
                settings.timeout = timeout;
                return $.ajax(settings);
            }
        }
        AppOrchard.API = API;
        class MessageBanner {
            constructor(id, text) {
                this.Id = 0;
                this.Text = "";
                this.Id = id;
                this.Text = text;
            }
        }
        AppOrchard.MessageBanner = MessageBanner;
        class CustomKOBindings {
            /**
             * Two way binding to allow editing HTML on the page directly. Created for questionnaire help text binding (see Questionnaire view),
             * but is parametrized to allow for other use cases.
             *
             * The element being bound must specify some parameters as follows:
            * <div data-bind="editableHtml: {html: <observableName>, selector: <selector>, events: <events>, callbacks: [<callbacks>] }>"
            *
            *     html:      name of observable member that will actually hold the HTML contents and be refernced in KO view model code.
            *     selector:  CSS/JQuery selector, starting from the bound element, to to identify where to bind event handlers that will update the observable value.
            *     events:    space-delimited list of events (using the editable HTML element as a starting point for selection) to bind the the observable updates to.
            *     callbacks: array literal of callbacks to execute on the HTML contents before updating the observable member with it.
            *
            * For example (from the Questionnaire):
            *   <div data-bind="editableHtml: { html: Helptext,
            *								selector: '~ button.saveButton, ~ button.cancelButton',
            *								events: 'click',
            *								callbacks: [Epic.AppOrchard.Util.RemoveTrailingBlankLines, Epic.AppOrchard.Util.SetLinksToOpenInNewTab] }">
            *
            * Note that the actual binding name is specified by the name of the property in the ko.bindingHandlers.<binding-name> call, so it doesn't need to be editableHtml per se.
            * */
            static EditableHtml() {
                return {
                    init: function (element, valueAccessor) {
                        var observable = ko.unwrap(valueAccessor());
                        var hasCallbacks = observable.callbacks && Array.isArray(observable.callbacks) && observable.callbacks.length > 0;
                        $(observable.selector, element).on(observable.events, function () {
                            if (hasCallbacks) {
                                for (var i = 0; i < observable.callbacks.length; i++) {
                                    observable.callbacks[i](element);
                                }
                            }
                            observable.html(($(element).html()));
                        });
                    },
                    update: function (element, valueAccessor) {
                        var observable = ko.utils.unwrapObservable(valueAccessor());
                        $(element).html(observable.html());
                    }
                };
            }
        }
        AppOrchard.CustomKOBindings = CustomKOBindings;
        class WindowWidthBinding {
            constructor() {
                this.Width = ko.observable(window.innerWidth);
                this.MobileWidthConstant = 992; //this is the number used by bootstrap
                this.IsMobileWidth = ko.computed(() => {
                    return (this.Width() <= this.MobileWidthConstant);
                }, this);
            }
            Resize() {
                this.Width(window.innerWidth);
            }
        }
        AppOrchard.WindowWidthBinding = WindowWidthBinding;
        class Field {
            constructor(label, type, startingValue = "", props = [], options = [], helptext = "", helptextLink = "", isRequired = false) {
                this.InputElement = null;
                this.Label = label;
                this.Helptext = helptext;
                this.HelptextLink = helptextLink;
                this.Type = type;
                this.StartingValue = startingValue;
                this.Props = props;
                this.Options = options;
                this.IsRequired = isRequired;
            }
            GetInputElement(fieldName) {
                if (this.InputElement == null) {
                    switch (this.Type) {
                        case FieldType.PassThroughValue:
                            this.InputElement = $("<input class='hidden' type='text' />");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.Text:
                            this.InputElement = $("<input class='modal-field form-control' type='text' />");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.Number:
                            this.InputElement = $("<input class='modal-field form-control' type='number' />");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.Select:
                            this.InputElement = $("<select class='modal-field form-control'></select>");
                            this.InputElement.prop("id", fieldName);
                            this.AppendOptions();
                            break;
                        case FieldType.Date:
                            this.InputElement = $("<input class='modal-field form-control' type='date'/>");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.MultiSelect:
                            this.InputElement = $("<span class='modal-field form-control collect-field-multiselect'></span>");
                            this.AppendOptionsAsCheckboxes();
                            break;
                        case FieldType.MultilineText:
                            this.InputElement = $("<textarea class='modal-field form-control' type='text'></textarea");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.Email:
                            this.InputElement = $("<input class='modal-field form-control' type='email' />");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.Url:
                            this.InputElement = $("<input class='modal-field form-control' type='url' />");
                            this.InputElement.prop("pattern", "((https:\/\/)|(http:\/\/)).+");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.AppCategories:
                            this.InputElement = $("<div class='modal-field form-inline collect-field-category'><!-- ko if: LoadingCategories--><span style='font-weight:normal;display:block;font-size:14px;'>Loading...</span><!-- /ko --><!-- ko ifnot: LoadingCategories--><!-- ko template: { name: 'AppCategoryCheckboxTreeTemplate', foreach: Categories }--><!-- /ko --><!-- /ko --></div>");
                            break;
                        case FieldType.Switch:
                            this.InputElement = $("<input class='collect-field-switch' style='display:block;height:25px;width:25px' type='checkbox' />");
                            this.InputElement.prop("id", fieldName);
                            break;
                        case FieldType.PrimaryAppCategory:
                            this.InputElement = $("<div class='modal-field form-inline collect-field-primary-category'><!-- ko if: LoadingCategories--><span style='font-weight:normal;display:block;font-size:14px;'>Loading...</span><!-- /ko --><!-- ko ifnot: LoadingCategories-->"
                                + "<select class='modal-field form-control' data-bind='options: $data.SelectedCategories, value: $data.PrimaryCategory_Id, optionsText: \"Name\", optionsValue: \"Id\", disable: $data.SelectedCategories().length == 0'></select>"
                                + "<!-- /ko --></div>");
                            break;
                        default:
                            throw "Unknown Field Type";
                    }
                }
                return this.InputElement;
            }
            GetHelptextElement(useTopPlacement) {
                if (this.Helptext) {
                    let dataPlacement = useTopPlacement ? "top" : "bottom";
                    let element;
                    if (this.HelptextLink) {
                        element = $("<a class=\"bootstrap-tooltip-icon glyphicon glyphicon-question-sign\" data-toggle=\"tooltip\" data-placement=\"" + dataPlacement + "\" tabindex=\"0\" target=\"_blank\"></a>");
                        element.prop("href", this.HelptextLink);
                    }
                    else {
                        element = $("<span class=\"bootstrap-tooltip-icon glyphicon glyphicon-question-sign\" data-toggle=\"tooltip\" data-placement=\"" + dataPlacement + "\" tabindex=\"0\"></span>");
                    }
                    element.prop("title", this.Helptext);
                    return element;
                }
                return null;
            }
            GetCharacterCounterElement(fieldName) {
                if (!this.Props || !Array.isArray(this.Props) || this.Type == FieldType.PassThroughValue) {
                    return null;
                }
                let inputElement = this.InputElement || this.GetInputElement(fieldName);
                const maxlength = AppOrchard.DbResources.KeyValuePairHelper.FindMatchingPairInArray("maxlength", this.Props, false);
                if (!maxlength || !inputElement) {
                    return null;
                }
                const maxlengthValue = parseInt(maxlength.Value);
                if (isNaN(maxlengthValue))
                    return null;
                if (!(inputElement.val() instanceof String)) {
                    return null;
                }
                let characterCounterElement = $("<p class='character-count' style='font-weight: normal;font-size: small;'></p>");
                const startingNumberOfCharacters = inputElement.val().length;
                const startingNumberOfCharactersRemaining = maxlengthValue - startingNumberOfCharacters;
                let text = "";
                if (startingNumberOfCharactersRemaining == 1) {
                    text = "1 character left";
                }
                else {
                    text = startingNumberOfCharactersRemaining + " characters left";
                }
                characterCounterElement.text(text);
                inputElement.on("input", function () {
                    const numberOfCharacters = $(this).val().length;
                    const numberOfCharactersRemaining = maxlengthValue - numberOfCharacters;
                    let text = "";
                    if (numberOfCharactersRemaining == 1) {
                        text = "1 character left";
                    }
                    else {
                        text = numberOfCharactersRemaining + " characters left";
                    }
                    characterCounterElement.text(text);
                });
                return characterCounterElement;
            }
            GetOnChangeFunction() {
                let fieldModel = this;
                return (event) => {
                    let element = event.target;
                    if (element.validity.valid) {
                        element.title = fieldModel.GetTitleFromProps();
                    }
                    else if (element.validity.typeMismatch) {
                        element.title = "Your browser does not recognize that as a valid URL. Ensure the value starts with an accepted protocol (http:// or https://)";
                    }
                    else {
                        element.title = "Provide a valid URL.";
                    }
                };
            }
            AppendOptions() {
                for (let optionIndex = 0; optionIndex < this.Options.length; optionIndex++) {
                    let optionElement = $("<option></option>");
                    optionElement.prop("value", this.Options[optionIndex].Value);
                    optionElement.text(this.Options[optionIndex].Key);
                    this.InputElement.append(optionElement);
                }
            }
            AppendOptionsAsCheckboxes() {
                if (this.Options.length == 0) {
                    this.InputElement.text("No records available.");
                    return;
                }
                for (let optionIndex = 0; optionIndex < this.Options.length; optionIndex++) {
                    let checkboxElement = $("<input type='checkbox' style='margin-right: 5px'/>");
                    checkboxElement.prop("value", this.Options[optionIndex].Value);
                    let labelElement = $("<label style='display: inline-block; padding-right: 10px; font-weight: normal;'></label>");
                    labelElement.append(checkboxElement);
                    labelElement.append(this.Options[optionIndex].Key);
                    this.InputElement.append(labelElement);
                }
            }
            GetTitleFromProps() {
                let matchingProps = this.Props.filter((value) => value.Key.toLocaleUpperCase() === "TITLE");
                if (matchingProps.length === 0) {
                    return "";
                }
                return matchingProps[0].Value;
            }
            static BuildOptionsForEnum(enumRef) {
                let result = [];
                for (var index in enumRef) {
                    var raw = index;
                    var asNum = +index;
                    if (!index ||
                        raw == asNum) {
                        continue;
                    }
                    var value = parseInt(enumRef[index]);
                    result.push({ Value: value.toString(), Key: Epic.AppOrchard.Helpers.PrettifyPascalCase(Epic.AppOrchard.Util.GetEnumValueName(value, enumRef)) });
                }
                return result;
            }
            static EmptyField(value) {
                return new Field("", FieldType.PassThroughValue, value);
            }
        }
        AppOrchard.Field = Field;
        (function (FieldType) {
            FieldType[FieldType["PassThroughValue"] = 0] = "PassThroughValue";
            FieldType[FieldType["Text"] = 1] = "Text";
            FieldType[FieldType["Number"] = 2] = "Number";
            FieldType[FieldType["Select"] = 3] = "Select";
            FieldType[FieldType["Date"] = 4] = "Date";
            FieldType[FieldType["MultiSelect"] = 5] = "MultiSelect";
            FieldType[FieldType["MultilineText"] = 6] = "MultilineText";
            FieldType[FieldType["Email"] = 7] = "Email";
            FieldType[FieldType["Url"] = 8] = "Url";
            FieldType[FieldType["AppCategories"] = 9] = "AppCategories";
            FieldType[FieldType["Switch"] = 10] = "Switch";
            FieldType[FieldType["PrimaryAppCategory"] = 11] = "PrimaryAppCategory";
        })(AppOrchard.FieldType || (AppOrchard.FieldType = {}));
        var FieldType = AppOrchard.FieldType;
        class QueryParameter {
            constructor(key, value) {
                this.Key = key;
                this.Value = value;
            }
            ToString() {
                return this.Key + "=" + this.Value;
            }
        }
        /**
         * Helpers for parsing/updating the query string
         * */
        class QueryString {
            constructor() {
                this.Parameters = [];
            }
            /**
             * Whether or not there are any parameters in this object
             */
            HasValues() {
                return this.Parameters.length > 0;
            }
            ToString() {
                return this.Parameters.map(function (value) { return value.ToString(); }).join("&");
            }
            /**
             * Get a key/value pair based on key
            * @param key key to find
            * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
             */
            Get(key, caseSensitive = false) {
                if (Epic.AppOrchard.Util.IsNullOrEmpty(key))
                    return null;
                if (caseSensitive) {
                    return this.Parameters.filter(function (value) { return value.Key == key; })[0];
                }
                else {
                    key = key.toUpperCase();
                    return this.Parameters.filter(function (value) { return value.Key.toUpperCase() == key; })[0];
                }
            }
            /**
            * Get the value for a key
            * @param key key to find
            * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
            */
            GetValue(key, caseSensitive = false) {
                const matchingParam = this.Get(key, caseSensitive);
                return matchingParam ? matchingParam.Value : "";
            }
            /**
            * Get the value for a key and convert it to a number
            * @param key key to find
            * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
            */
            GetValueAsNumber(key, caseSensitive = false) {
                const valueAsString = this.GetValue(key, caseSensitive);
                return Epic.AppOrchard.Util.ParamToNumber(valueAsString);
            }
            /**
            * Get the value for a key and convert it to a number array
            * @param key key to find
            * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
            */
            GetValueAsNumberList(key, caseSensitive = false) {
                const valueAsString = this.GetValue(key, caseSensitive);
                return Epic.AppOrchard.Util.ParamToNumberList(valueAsString);
            }
            /**
            * Remove key/value pair
            * @param key query key to remove
            * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
            */
            Remove(key, caseSensitive = false) {
                if (caseSensitive) {
                    this.Parameters = this.Parameters.filter(function (value) { return value.Key != key; });
                }
                else {
                    key = key.toUpperCase();
                    this.Parameters = this.Parameters.filter(function (value) { return value.Key.toUpperCase() != key; });
                }
            }
            /**
            * Upsert (insert or update if exists) value for a given key
            * @param key query key to insert/update
            * @param value query value to insert/update
            * @param caseSensitive whether to use case sensitive comparison to find key to insert/update, default is case insensitive
            */
            Upsert(key, value, caseSensitive = false) {
                let existingParameter = this.Get(key, caseSensitive);
                if (existingParameter) {
                    existingParameter.Value = value;
                }
                else {
                    this.Parameters.push(new QueryParameter(key, value));
                }
            }
            /**
             * Update the URL history using the current state
             * @param replaceState whether to replace history state (true) or push history state (false/default)
             * @param callOnHashChange whether to call onHashChange handlers
             */
            UpdateUrl(replaceState, callOnHashChange) {
                AppOrchard.PageLoad.InjectNewUrlToHistory(this.ToString(), replaceState, callOnHashChange);
            }
            /**
             * Construct QueryString object from a URL
             * @param url URL to create query string from, if not passed, window.location.search will be used
             */
            static BuildFromUrl(url) {
                const queryString = new QueryString();
                if (Util.IsNullOrEmpty(url))
                    url = window.location.search;
                if (!Util.IsNullOrEmpty(url)) {
                    const query = url.split("?")[1];
                    const params = query.split("&");
                    for (let i = 0; i < params.length; i++) {
                        const kvPair = params[i].split("=");
                        const key = decodeURIComponent(kvPair[0]);
                        const value = decodeURIComponent(kvPair[1]);
                        queryString.Upsert(key, value);
                    }
                }
                return queryString;
            }
            /**
             * Upsert (insert or update if exists) value for a given key to the URL and add to history
             * @param key query key to insert/update
             * @param value query value to insert/update
             * @param replaceState whether to replace history state (true) or push history state (false/default)
             * @param callOnHashChange whether to call onHashChange handlers
             * @param url URL to update, if not passed, window.location.search will be used
             * @param caseSensitive whether to use case sensitive comparison to find key to insert/update, default is case insensitive
             */
            static UpsertToUrl(key, value, replaceState, callOnHashChange, url, caseSensitive = false) {
                const queryString = this.BuildFromUrl(url);
                queryString.Upsert(key, value, caseSensitive);
                AppOrchard.PageLoad.InjectNewUrlToHistory(queryString.ToString(), replaceState, callOnHashChange);
            }
            /**
            * Remove key/value pair from the URL and add to history
            * @param key query key to remove
            * @param replaceState whether to replace history state (true) or push history state (false/default)
            * @param callOnHashChange whether to call onHashChange handlers
            * @param url URL to update, if not passed, window.location.search will be used
            * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
            */
            static RemoveFromUrl(key, replaceState, callOnHashChange, url, caseSensitive = false) {
                const queryString = this.BuildFromUrl(url);
                queryString.Remove(key, caseSensitive);
                AppOrchard.PageLoad.InjectNewUrlToHistory(queryString.ToString(), replaceState, callOnHashChange);
            }
            /**
            * Remove all query params from the current URL
            * @param replaceState whether to replace history state (true) or push history state (false/default)
            * @param callOnHashChange whether to call onHashChange handlers
            */
            static RemoveAllFromUrl(replaceState, callOnHashChange) {
                AppOrchard.PageLoad.InjectNewUrlToHistory("", replaceState, callOnHashChange);
            }
            /**
             * Get the value for a key
             * @param key key to find
             * @param url URL to search in, if not passed, window.location.search will be used
             * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
             */
            static GetValue(key, url, caseSensitive = false) {
                const queryString = this.BuildFromUrl(url);
                return queryString.GetValue(key, caseSensitive);
            }
            /**
             * Get the value for a key and convert it to a number
             * @param key key to find
             * @param url URL to search in, if not passed, window.location.search will be used
             * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
             */
            static GetValueAsNumber(key, url, caseSensitive = false) {
                const valueAsString = this.GetValue(key, url, caseSensitive);
                return Epic.AppOrchard.Util.ParamToNumber(valueAsString);
            }
            /**
            * Get the value for a key and convert it to a number array
            * @param key key to find
            * @param caseSensitive whether to use case sensitive comparison to find key to delete, default is case insensitive
            */
            static GetValueAsNumberList(key, url, caseSensitive = false) {
                const valueAsString = this.GetValue(key, url, caseSensitive);
                return Epic.AppOrchard.Util.ParamToNumberList(valueAsString);
            }
        }
        AppOrchard.QueryString = QueryString;
    })(AppOrchard = Epic.AppOrchard || (Epic.AppOrchard = {}));
})(Epic || (Epic = {}));
//# sourceMappingURL=epic.core.js.map;/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/knockout/knockout.d.ts" />
/// <reference path="typings/bootstrap/bootstrap.d.ts" />
/// <reference path="typings/knockout.mapping/knockout.mapping.d.ts" />
/// <reference path="Epic.Core.ts" />
var Epic;
(function (Epic) {
    var AppOrchard;
    (function (AppOrchard) {
        class Shell {
            /** Initializes the shared context settings for settings defined on the server.
             * @param (number) logoutIdleTimeInMinutes - The number of minutes that can ellapse before a user is forced to logout.
             */
            static InitializeContext(logoutIdleTimeInMinutes) {
                Epic.AppOrchard.Shell._logoutIdleTimeInMinutes = logoutIdleTimeInMinutes;
                // register the keep-alive function in the window to ensure actions taken by the user will persist the session
                $(window).keyup(this.OnUserKeyAction);
                $(window).mousedown(this.OnUserMouseAction);
                $(function () {
                    Epic.AppOrchard.Shell.ResetLogoutTimer();
                });
            }
            /** Force the logout of the user session */
            static ForceLogout() {
                Epic.AppOrchard.Shell._forceLogout = true;
                window.location.href = Epic.AppOrchard.Shell.GetLogoutPath();
            }
            static IsForceLogout() {
                return Epic.AppOrchard.Shell._forceLogout;
            }
            /** Reset the timer for forcing the logout, this is typically done on user interaction. */
            static ResetLogoutTimer(idleTimeout = 0) {
                if (!Epic.AppOrchard.Shell._logoutIdleTimeInMinutes) {
                    //If not set, use default
                    Epic.AppOrchard.Shell._logoutIdleTimeInMinutes = 59;
                }
                //make sure the user is even logged in.  If they're not, we can't log them out.
                if (Epic.AppOrchard.Util.IsNullOrEmpty(Epic.AppOrchard.Util.Username())) {
                    return;
                }
                if (Epic.AppOrchard.Shell._logoutWarningEventTimer) {
                    window.clearTimeout(Epic.AppOrchard.Shell._logoutWarningEventTimer);
                }
                else {
                    Epic.AppOrchard.Util.HideLogoutWarning();
                }
                if (Epic.AppOrchard.Shell._logoutEventTimer) {
                    window.clearTimeout(Epic.AppOrchard.Shell._logoutEventTimer);
                }
                if (idleTimeout <= 0) {
                    idleTimeout = (Epic.AppOrchard.Shell._logoutIdleTimeInMinutes - 1) * 60000;
                }
                Epic.AppOrchard.Shell._logoutWarningEventTimer = window.setTimeout(Epic.AppOrchard.Shell.ShouldShowLogoutWarning, idleTimeout);
            }
            static ShouldShowLogoutWarning(fromWarningDialog = false) {
                var defaultWarningTimeout = (Epic.AppOrchard.Shell._logoutIdleTimeInMinutes - 1) * 60000;
                Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST // validate if session is alive on the server
                , "/Account/GetIdleTime", true, {}, (data, textStatus, jqXHR) => {
                    if (data && (parseInt(data) < defaultWarningTimeout)) {
                        Epic.AppOrchard.Shell.ResetLogoutTimer(defaultWarningTimeout - parseInt(data));
                        return;
                    }
                    if (!fromWarningDialog) {
                        Epic.AppOrchard.Shell.DisplayLogoutWarning();
                    }
                }, (jqXHR, textStatus, errorThrown) => {
                    if (!fromWarningDialog) {
                        Epic.AppOrchard.Shell.DisplayLogoutWarning();
                    }
                }, 10000, false, null, true);
            }
            static DisplayLogoutWarning() {
                Epic.AppOrchard.Shell._logoutWarningEventTimer = null;
                Epic.AppOrchard.Util.ShowLogoutWarning();
                Epic.AppOrchard.Shell.UpdateCountdownTimer();
                Epic.AppOrchard.Shell._logoutEventTimer = window.setTimeout(Epic.AppOrchard.Shell.ForceLogout, 60000);
                $("#LogoutWarningForScreenReader").text("");
            }
            static UpdateCountdownTimer(secondsRemaining = 60) {
                if (secondsRemaining >= 0 && Epic.AppOrchard.Util.IsLogoutWarning()) {
                    $("#LogoutWarningDialogueTimer").text(secondsRemaining);
                    if (--secondsRemaining % 5 == 0)
                        Epic.AppOrchard.Shell.ShouldShowLogoutWarning(true);
                    if (secondsRemaining % 10 == 0)
                        $("#LogoutWarningForScreenReader").text($("#LogoutWarningText").text());
                    Epic.AppOrchard.Shell.ShouldShowLogoutWarning(true);
                    window.setTimeout(Epic.AppOrchard.Shell.UpdateCountdownTimer, 1000, secondsRemaining);
                }
            }
            /** For the logout, but only if the session is expired. */
            static ForceLogoutOrRefreshSession(result, setting) {
                if (result != null) {
                    if (result.Message != null && result.Message == Epic.AppOrchard.Shell.ErrorCodeForSessionExpired) {
                        Epic.AppOrchard.Shell.ForceLogout();
                        return true;
                    }
                    else if (result.Message != null && result.Message == Epic.AppOrchard.Shell.ErrorCodeForFederatedSessionExpired) {
                        QuickSignInShow(Epic.AppOrchard.Util.GetFullUrl("Account/SignIn?returnUrl=/Account/QuickSignIn"), $.proxy(function () { $.ajax(setting); }, this), null, null, false);
                    }
                }
                return false;
            }
            static OnUserKeyAction(ev) {
                Epic.AppOrchard.Shell.OnAction();
            }
            static OnUserMouseAction(eventData) {
                Epic.AppOrchard.Shell.OnAction();
            }
            static OnAction() {
                // since the timer is currently defined there is no need to do additional work as we are throttling the callbacks
                if (Epic.AppOrchard.Shell._onUserActionCallbackTimer) {
                    return;
                }
                // set a timer for 5 seconds to reset our timer to ensure we send another keep-alive in a few seconds
                this._onUserActionCallbackTimer = window.setTimeout(function () {
                    if (Epic.AppOrchard.Shell._onUserActionCallbackTimer) {
                        window.clearTimeout(Epic.AppOrchard.Shell._onUserActionCallbackTimer);
                    }
                    Epic.AppOrchard.Shell._onUserActionCallbackTimer = null;
                }, 5000);
                // validate the session on the server
                Epic.AppOrchard.API.ExecuteAjax(Epic.AppOrchard.HttpMethod.POST, "/Account/ValidateSession", true, null, null, null);
            }
            static GetLogoutPath() {
                return Epic.AppOrchard.Util.GetFullUrl("Account/Logoff?returnUrl=" + encodeURIComponent(window.location.pathname + window.location.search + window.location.hash) + "&forcedLogout=true");
            }
        }
        Shell.ErrorCodeForSessionExpired = "SESSION-EXPIRED";
        Shell.ErrorCodeForFederatedSessionExpired = "FEDERATED-SESSION-EXPIRED";
        AppOrchard.Shell = Shell;
    })(AppOrchard = Epic.AppOrchard || (Epic.AppOrchard = {}));
})(Epic || (Epic = {}));
//# sourceMappingURL=Epic.Shell.js.map;//----------------------------------------------------
// Copyright 2016-2023 Epic Systems Corporation
//----------------------------------------------------
/// <reference path="typings/jquery/jquery.d.ts" />
/// <reference path="typings/knockout/knockout.d.ts" />
/// <reference path="typings/bootstrap/bootstrap.d.ts" />
/// <reference path="typings/knockout.mapping/knockout.mapping.d.ts" />
/// <reference path="AppQuestionnaire.ts" />
var Epic;
(function (Epic) {
    var AppOrchard;
    (function (AppOrchard) {
        var DbResources;
        (function (DbResources) {
            DbResources.NewRecordId = -1;
            DbResources.AppBackgroundColors = ["#6d55a3", "#e72f6c", "#0091ea", "#61d8e5", "#ff4d4d", "#cf3eff", "#ff64a0", "#4ddb64"];
            DbResources.AppCategoryIcons = ["tag", "briefcase", "usd glyphicon-usd-margin-right", "piggy-bank", "comment", "heart", "user", "globe", "stats", "signal", "search", "cloud", "envelope", "earphone", "facetime-video", "cog", "wrench", "time", "hourglass", "print", "bullhorn"];
            const CustomUriPrefix = "custom";
            const HttpUriPrefix = "http://";
            DbResources.HttpsUriPrefix = "https://";
            //#region enums
            (function (AuthorizedApiComplexity) {
                AuthorizedApiComplexity[AuthorizedApiComplexity["Low"] = 0] = "Low";
                AuthorizedApiComplexity[AuthorizedApiComplexity["Medium"] = 1] = "Medium";
                AuthorizedApiComplexity[AuthorizedApiComplexity["High"] = 3] = "High";
            })(DbResources.AuthorizedApiComplexity || (DbResources.AuthorizedApiComplexity = {}));
            var AuthorizedApiComplexity = DbResources.AuthorizedApiComplexity;
            (function (AuthorizedApiDevBucket) {
                AuthorizedApiDevBucket[AuthorizedApiDevBucket["Low"] = 0] = "Low";
                AuthorizedApiDevBucket[AuthorizedApiDevBucket["Medium"] = 1] = "Medium";
                AuthorizedApiDevBucket[AuthorizedApiDevBucket["High"] = 3] = "High";
            })(DbResources.AuthorizedApiDevBucket || (DbResources.AuthorizedApiDevBucket = {}));
            var AuthorizedApiDevBucket = DbResources.AuthorizedApiDevBucket;
            (function (AuthorizedApiRisk) {
                AuthorizedApiRisk[AuthorizedApiRisk["Low"] = 0] = "Low";
                AuthorizedApiRisk[AuthorizedApiRisk["Medium"] = 1] = "Medium";
                AuthorizedApiRisk[AuthorizedApiRisk["High"] = 3] = "High";
            })(DbResources.AuthorizedApiRisk || (DbResources.AuthorizedApiRisk = {}));
            var AuthorizedApiRisk = DbResources.AuthorizedApiRisk;
            (function (AuthorizedApiSourceType) {
                AuthorizedApiSourceType[AuthorizedApiSourceType["Report"] = 0] = "Report";
                AuthorizedApiSourceType[AuthorizedApiSourceType["Registry"] = 1] = "Registry";
                AuthorizedApiSourceType[AuthorizedApiSourceType["Metric"] = 2] = "Metric";
                AuthorizedApiSourceType[AuthorizedApiSourceType["WebService"] = 3] = "WebService";
                AuthorizedApiSourceType[AuthorizedApiSourceType["PrintGroup"] = 4] = "PrintGroup";
                AuthorizedApiSourceType[AuthorizedApiSourceType["Clarity"] = 5] = "Clarity";
            })(DbResources.AuthorizedApiSourceType || (DbResources.AuthorizedApiSourceType = {}));
            var AuthorizedApiSourceType = DbResources.AuthorizedApiSourceType;
            (function (ProgramLevel) {
                ProgramLevel[ProgramLevel["Undefined"] = 0] = "Undefined";
                ProgramLevel[ProgramLevel["USCDIMember"] = 50] = "USCDIMember";
                ProgramLevel[ProgramLevel["BronzeMinus"] = 90] = "BronzeMinus";
                ProgramLevel[ProgramLevel["Bronze"] = 100] = "Bronze";
                ProgramLevel[ProgramLevel["Silver"] = 200] = "Silver";
                ProgramLevel[ProgramLevel["Gold"] = 300] = "Gold";
                ProgramLevel[ProgramLevel["EpicCommunityMember"] = 500] = "EpicCommunityMember";
                ProgramLevel[ProgramLevel["Epic"] = 1000] = "Epic";
            })(DbResources.ProgramLevel || (DbResources.ProgramLevel = {}));
            var ProgramLevel = DbResources.ProgramLevel;
            (function (EmailTemplates) {
                EmailTemplates[EmailTemplates["UserActivated"] = 1] = "UserActivated";
                EmailTemplates[EmailTemplates["UserPasswordReset"] = 2] = "UserPasswordReset";
                EmailTemplates[EmailTemplates["OrganizationInterestedThankYou"] = 1000] = "OrganizationInterestedThankYou";
                EmailTemplates[EmailTemplates["OrganizationApproved"] = 1001] = "OrganizationApproved";
                EmailTemplates[EmailTemplates["ProgramRequested"] = 1010] = "ProgramRequested";
                EmailTemplates[EmailTemplates["ProgramLevelApproved"] = 1020] = "ProgramLevelApproved";
                EmailTemplates[EmailTemplates["ApplicationHasBeenSubmitted"] = 2000] = "ApplicationHasBeenSubmitted";
                EmailTemplates[EmailTemplates["ApplicationHasBeenApproved"] = 2001] = "ApplicationHasBeenApproved";
                EmailTemplates[EmailTemplates["ApplicationDownloadRequested"] = 2003] = "ApplicationDownloadRequested";
                EmailTemplates[EmailTemplates["ApplicationDownloadApproved"] = 2004] = "ApplicationDownloadApproved";
                EmailTemplates[EmailTemplates["ApplicationChangesRequested"] = 2005] = "ApplicationChangesRequested";
                EmailTemplates[EmailTemplates["ApplicationHasNewInterest"] = 2010] = "ApplicationHasNewInterest";
                EmailTemplates[EmailTemplates["NotificationMarketplaceAvailable"] = 10000] = "NotificationMarketplaceAvailable";
            })(DbResources.EmailTemplates || (DbResources.EmailTemplates = {}));
            var EmailTemplates = DbResources.EmailTemplates;
            (function (UserAccountType) {
                UserAccountType[UserAccountType["Undefined"] = 0] = "Undefined";
                UserAccountType[UserAccountType["Queued"] = 10] = "Queued";
                UserAccountType[UserAccountType["PendingApproval"] = 50] = "PendingApproval";
                UserAccountType[UserAccountType["VendorDeveloper"] = 100] = "VendorDeveloper";
                UserAccountType[UserAccountType["EpicUser"] = 200] = "EpicUser";
                UserAccountType[UserAccountType["VendorAdmin"] = 400] = "VendorAdmin";
                UserAccountType[UserAccountType["EpicAdmin"] = 800] = "EpicAdmin";
                UserAccountType[UserAccountType["SuperAdministrator"] = 1000] = "SuperAdministrator";
            })(DbResources.UserAccountType || (DbResources.UserAccountType = {}));
            var UserAccountType = DbResources.UserAccountType;
            (function (OrganizationStatus) {
                OrganizationStatus[OrganizationStatus["Undefined"] = 0] = "Undefined";
                OrganizationStatus[OrganizationStatus["Interested"] = 1] = "Interested";
                OrganizationStatus[OrganizationStatus["OrganizationDenied"] = 2] = "OrganizationDenied";
                OrganizationStatus[OrganizationStatus["OrganizationApproved"] = 3] = "OrganizationApproved";
                OrganizationStatus[OrganizationStatus["RequestingProgramLevel"] = 4] = "RequestingProgramLevel";
                OrganizationStatus[OrganizationStatus["ProgramLevelDenied"] = 5] = "ProgramLevelDenied";
                OrganizationStatus[OrganizationStatus["Invoicing"] = 6] = "Invoicing";
                OrganizationStatus[OrganizationStatus["PaymentFailed"] = 7] = "PaymentFailed";
                OrganizationStatus[OrganizationStatus["ProgramLevelApproved"] = 8] = "ProgramLevelApproved";
                OrganizationStatus[OrganizationStatus["VendorDiscontinued"] = 9] = "VendorDiscontinued";
            })(DbResources.OrganizationStatus || (DbResources.OrganizationStatus = {}));
            var OrganizationStatus = DbResources.OrganizationStatus;
            (function (OrganizationUserAssociation) {
                OrganizationUserAssociation[OrganizationUserAssociation["Undefined"] = 0] = "Undefined";
                OrganizationUserAssociation[OrganizationUserAssociation["InitialContact"] = 1] = "InitialContact";
                OrganizationUserAssociation[OrganizationUserAssociation["EpicOwner"] = 2] = "EpicOwner";
                OrganizationUserAssociation[OrganizationUserAssociation["DirectEmployee"] = 3] = "DirectEmployee";
                OrganizationUserAssociation[OrganizationUserAssociation["RemoteAccess"] = 4] = "RemoteAccess";
            })(DbResources.OrganizationUserAssociation || (DbResources.OrganizationUserAssociation = {}));
            var OrganizationUserAssociation = DbResources.OrganizationUserAssociation;
            (function (ClientApplicationStatus) {
                ClientApplicationStatus[ClientApplicationStatus["Draft"] = 0] = "Draft";
                ClientApplicationStatus[ClientApplicationStatus["Internal"] = 50] = "Internal";
                ClientApplicationStatus[ClientApplicationStatus["Submitted"] = 100] = "Submitted";
                ClientApplicationStatus[ClientApplicationStatus["InReview"] = 200] = "InReview";
                ClientApplicationStatus[ClientApplicationStatus["ChangeRequested"] = 300] = "ChangeRequested";
                ClientApplicationStatus[ClientApplicationStatus["ReadyToPublish"] = 400] = "ReadyToPublish";
                ClientApplicationStatus[ClientApplicationStatus["UscdiReleased"] = 475] = "UscdiReleased";
                ClientApplicationStatus[ClientApplicationStatus["Active"] = 500] = "Active";
                ClientApplicationStatus[ClientApplicationStatus["InActive"] = 900] = "InActive"; // UnPublished, may be because new version is available
            })(DbResources.ClientApplicationStatus || (DbResources.ClientApplicationStatus = {}));
            var ClientApplicationStatus = DbResources.ClientApplicationStatus;
            (function (ClientApplicationConsumerType) {
                ClientApplicationConsumerType[ClientApplicationConsumerType["Undefined"] = 0] = "Undefined";
                ClientApplicationConsumerType[ClientApplicationConsumerType["Employees"] = 100] = "Employees";
                ClientApplicationConsumerType[ClientApplicationConsumerType["Patient"] = 200] = "Patient";
                ClientApplicationConsumerType[ClientApplicationConsumerType["Backend"] = 300] = "Backend";
                ClientApplicationConsumerType[ClientApplicationConsumerType["PatientContact"] = 400] = "PatientContact";
            })(DbResources.ClientApplicationConsumerType || (DbResources.ClientApplicationConsumerType = {}));
            var ClientApplicationConsumerType = DbResources.ClientApplicationConsumerType;
            (function (PriceMode) {
                PriceMode[PriceMode["Undefined"] = 0] = "Undefined";
                PriceMode[PriceMode["Free"] = 1] = "Free";
                PriceMode[PriceMode["Paid"] = 2] = "Paid";
            })(DbResources.PriceMode || (DbResources.PriceMode = {}));
            var PriceMode = DbResources.PriceMode;
            (function (DownloadApprovedStatus) {
                DownloadApprovedStatus[DownloadApprovedStatus["Unapproved"] = 0] = "Unapproved";
                DownloadApprovedStatus[DownloadApprovedStatus["Approved"] = 1] = "Approved";
                DownloadApprovedStatus[DownloadApprovedStatus["Declined"] = 2] = "Declined";
                DownloadApprovedStatus[DownloadApprovedStatus["NonProdOnly"] = 3] = "NonProdOnly";
                DownloadApprovedStatus[DownloadApprovedStatus["Overwritten"] = 4] = "Overwritten";
            })(DbResources.DownloadApprovedStatus || (DbResources.DownloadApprovedStatus = {}));
            var DownloadApprovedStatus = DbResources.DownloadApprovedStatus;
            (function (SecurityPolicy) {
                SecurityPolicy[SecurityPolicy["Undefined"] = 0] = "Undefined";
                SecurityPolicy[SecurityPolicy["UsernameToken"] = 1] = "UsernameToken";
                SecurityPolicy[SecurityPolicy["OAuth2"] = 2] = "OAuth2";
            })(DbResources.SecurityPolicy || (DbResources.SecurityPolicy = {}));
            var SecurityPolicy = DbResources.SecurityPolicy;
            (function (CGAppType) {
                CGAppType[CGAppType["Other"] = 0] = "Other";
                CGAppType[CGAppType["Unknown"] = 1] = "Unknown";
                CGAppType[CGAppType["OpenEpic"] = 2] = "OpenEpic";
                CGAppType[CGAppType["AO"] = 3] = "AO";
                CGAppType[CGAppType["MyOrg"] = 4] = "MyOrg";
            })(DbResources.CGAppType || (DbResources.CGAppType = {}));
            var CGAppType = DbResources.CGAppType;
            (function (QuestionnaireType) {
                QuestionnaireType[QuestionnaireType["Undefined"] = -1] = "Undefined";
                QuestionnaireType[QuestionnaireType["AppListing"] = 0] = "AppListing";
                QuestionnaireType[QuestionnaireType["DataGovernance"] = 1] = "DataGovernance";
            })(DbResources.QuestionnaireType || (DbResources.QuestionnaireType = {}));
            var QuestionnaireType = DbResources.QuestionnaireType;
            (function (QuestionnaireQuestionType) {
                QuestionnaireQuestionType[QuestionnaireQuestionType["Freetext"] = 0] = "Freetext";
                QuestionnaireQuestionType[QuestionnaireQuestionType["Radio"] = 1] = "Radio";
                QuestionnaireQuestionType[QuestionnaireQuestionType["Checkboxes"] = 2] = "Checkboxes";
            })(DbResources.QuestionnaireQuestionType || (DbResources.QuestionnaireQuestionType = {}));
            var QuestionnaireQuestionType = DbResources.QuestionnaireQuestionType;
            (function (QuestionnaireReviewStatus) {
                QuestionnaireReviewStatus[QuestionnaireReviewStatus["NotRequested"] = 0] = "NotRequested";
                QuestionnaireReviewStatus[QuestionnaireReviewStatus["Requested"] = 1] = "Requested";
                QuestionnaireReviewStatus[QuestionnaireReviewStatus["ChangesRecommended"] = 2] = "ChangesRecommended";
                QuestionnaireReviewStatus[QuestionnaireReviewStatus["Completed"] = 3] = "Completed";
            })(DbResources.QuestionnaireReviewStatus || (DbResources.QuestionnaireReviewStatus = {}));
            var QuestionnaireReviewStatus = DbResources.QuestionnaireReviewStatus;
            (function (API_Type) {
                API_Type[API_Type["Undefined"] = 0] = "Undefined";
                API_Type[API_Type["ComplexDerivedData"] = 1] = "ComplexDerivedData";
                API_Type[API_Type["Write"] = 2] = "Write";
                API_Type[API_Type["Read"] = 3] = "Read";
                API_Type[API_Type["Helper"] = 4] = "Helper";
                API_Type[API_Type["Search"] = 5] = "Search";
                API_Type[API_Type["Encounter_Level"] = 6] = "Encounter_Level";
                API_Type[API_Type["Patient_Level"] = 7] = "Patient_Level";
                API_Type[API_Type["FileTransferOrExport"] = 8] = "FileTransferOrExport";
            })(DbResources.API_Type || (DbResources.API_Type = {}));
            var API_Type = DbResources.API_Type;
            (function (EnvironmentType) {
                EnvironmentType[EnvironmentType["Sandbox"] = 0] = "Sandbox";
                EnvironmentType[EnvironmentType["Nonprod"] = 1] = "Nonprod";
                EnvironmentType[EnvironmentType["Prod"] = 2] = "Prod";
                EnvironmentType[EnvironmentType["Both"] = 3] = "Both";
            })(DbResources.EnvironmentType || (DbResources.EnvironmentType = {}));
            var EnvironmentType = DbResources.EnvironmentType;
            (function (Protocol) {
                Protocol[Protocol["http"] = 1] = "http";
                Protocol[Protocol["https"] = 2] = "https";
                Protocol[Protocol["custom"] = 3] = "custom";
            })(DbResources.Protocol || (DbResources.Protocol = {}));
            var Protocol = DbResources.Protocol;
            (function (InstallStatus) {
                InstallStatus[InstallStatus["NotStarted"] = 0] = "NotStarted";
                InstallStatus[InstallStatus["InProgress"] = 10] = "InProgress";
                InstallStatus[InstallStatus["Live"] = 20] = "Live";
                InstallStatus[InstallStatus["Deactivated"] = 30] = "Deactivated";
            })(DbResources.InstallStatus || (DbResources.InstallStatus = {}));
            var InstallStatus = DbResources.InstallStatus;
            (function (ReviewEndUserSelections) {
                ReviewEndUserSelections[ReviewEndUserSelections["Null"] = 0] = "Null";
                ReviewEndUserSelections[ReviewEndUserSelections["Yes"] = 1] = "Yes";
                ReviewEndUserSelections[ReviewEndUserSelections["No"] = 2] = "No";
            })(DbResources.ReviewEndUserSelections || (DbResources.ReviewEndUserSelections = {}));
            var ReviewEndUserSelections = DbResources.ReviewEndUserSelections;
            (function (ReviewOpinionSelections) {
                ReviewOpinionSelections[ReviewOpinionSelections["Null"] = 0] = "Null";
                ReviewOpinionSelections[ReviewOpinionSelections["Personal"] = 1] = "Personal";
                ReviewOpinionSelections[ReviewOpinionSelections["Organization"] = 2] = "Organization";
            })(DbResources.ReviewOpinionSelections || (DbResources.ReviewOpinionSelections = {}));
            var ReviewOpinionSelections = DbResources.ReviewOpinionSelections;
            (function (ReviewStakeSelections) {
                ReviewStakeSelections[ReviewStakeSelections["Null"] = 0] = "Null";
                ReviewStakeSelections[ReviewStakeSelections["Yes"] = 1] = "Yes";
                ReviewStakeSelections[ReviewStakeSelections["No"] = 2] = "No";
                ReviewStakeSelections[ReviewStakeSelections["Unknown"] = 3] = "Unknown";
            })(DbResources.ReviewStakeSelections || (DbResources.ReviewStakeSelections = {}));
            var ReviewStakeSelections = DbResources.ReviewStakeSelections;
            (function (ReviewCompensationSelections) {
                ReviewCompensationSelections[ReviewCompensationSelections["Null"] = 0] = "Null";
                ReviewCompensationSelections[ReviewCompensationSelections["Yes"] = 1] = "Yes";
                ReviewCompensationSelections[ReviewCompensationSelections["No"] = 2] = "No";
                ReviewCompensationSelections[ReviewCompensationSelections["Unknown"] = 3] = "Unknown";
            })(DbResources.ReviewCompensationSelections || (DbResources.ReviewCompensationSelections = {}));
            var ReviewCompensationSelections = DbResources.ReviewCompensationSelections;
            (function (ReviewResponseValue) {
                ReviewResponseValue[ReviewResponseValue["Null"] = 0] = "Null";
                ReviewResponseValue[ReviewResponseValue["Positive"] = 1] = "Positive";
                ReviewResponseValue[ReviewResponseValue["Negative"] = 2] = "Negative";
            })(DbResources.ReviewResponseValue || (DbResources.ReviewResponseValue = {}));
            var ReviewResponseValue = DbResources.ReviewResponseValue;
            (function (EventOrganizationAssociation) {
                EventOrganizationAssociation[EventOrganizationAssociation["None"] = 0] = "None";
                EventOrganizationAssociation[EventOrganizationAssociation["Owner"] = 1] = "Owner";
                EventOrganizationAssociation[EventOrganizationAssociation["Consumer"] = 2] = "Consumer";
            })(DbResources.EventOrganizationAssociation || (DbResources.EventOrganizationAssociation = {}));
            var EventOrganizationAssociation = DbResources.EventOrganizationAssociation;
            (function (EventEmailFrequency) {
                EventEmailFrequency[EventEmailFrequency["NoUpdates"] = 0] = "NoUpdates";
                EventEmailFrequency[EventEmailFrequency["DailyUpdates"] = 1] = "DailyUpdates";
                EventEmailFrequency[EventEmailFrequency["WeeklyUpdates"] = 7] = "WeeklyUpdates";
            })(DbResources.EventEmailFrequency || (DbResources.EventEmailFrequency = {}));
            var EventEmailFrequency = DbResources.EventEmailFrequency;
            (function (EventAccountType) {
                EventAccountType[EventAccountType["Undefined"] = 0] = "Undefined";
                EventAccountType[EventAccountType["VendorDev"] = 1] = "VendorDev";
                EventAccountType[EventAccountType["VendorAdmin"] = 2] = "VendorAdmin";
                EventAccountType[EventAccountType["Customer"] = 10] = "Customer";
                EventAccountType[EventAccountType["CanManageUsers"] = 11] = "CanManageUsers";
                EventAccountType[EventAccountType["CanPurchaseApps"] = 12] = "CanPurchaseApps";
                EventAccountType[EventAccountType["CanSubmitApps"] = 13] = "CanSubmitApps";
                EventAccountType[EventAccountType["CanActivateClients"] = 14] = "CanActivateClients";
                EventAccountType[EventAccountType["CanCreateRemoteApps"] = 15] = "CanCreateRemoteApps";
                EventAccountType[EventAccountType["EpicUser"] = 20] = "EpicUser";
                EventAccountType[EventAccountType["EpicAdmin"] = 21] = "EpicAdmin";
            })(DbResources.EventAccountType || (DbResources.EventAccountType = {}));
            var EventAccountType = DbResources.EventAccountType;
            (function (ContentValidationStatus) {
                ContentValidationStatus[ContentValidationStatus["Any"] = 0] = "Any";
                ContentValidationStatus[ContentValidationStatus["Done"] = 1] = "Done";
                ContentValidationStatus[ContentValidationStatus["InProgress"] = 2] = "InProgress";
                ContentValidationStatus[ContentValidationStatus["Error"] = 3] = "Error";
            })(DbResources.ContentValidationStatus || (DbResources.ContentValidationStatus = {}));
            var ContentValidationStatus = DbResources.ContentValidationStatus;
            (function (SubspaceOptionality) {
                SubspaceOptionality[SubspaceOptionality["Optional"] = 0] = "Optional";
                SubspaceOptionality[SubspaceOptionality["Required"] = 1] = "Required";
            })(DbResources.SubspaceOptionality || (DbResources.SubspaceOptionality = {}));
            var SubspaceOptionality = DbResources.SubspaceOptionality;
            (function (FhirIdVersionType) {
                FhirIdVersionType[FhirIdVersionType["VersionA"] = 1] = "VersionA";
                FhirIdVersionType[FhirIdVersionType["VersionB"] = 2] = "VersionB";
                FhirIdVersionType[FhirIdVersionType["Any"] = 999] = "Any";
            })(DbResources.FhirIdVersionType || (DbResources.FhirIdVersionType = {}));
            var FhirIdVersionType = DbResources.FhirIdVersionType;
            (function (ContactSubject) {
                ContactSubject[ContactSubject["Undefined"] = 0] = "Undefined";
                ContactSubject[ContactSubject["GeneralInquiry"] = 1] = "GeneralInquiry";
                ContactSubject[ContactSubject["TechnicalQuestion"] = 2] = "TechnicalQuestion";
                ContactSubject[ContactSubject["ShowroomInquiry"] = 3] = "ShowroomInquiry";
            })(DbResources.ContactSubject || (DbResources.ContactSubject = {}));
            var ContactSubject = DbResources.ContactSubject;
            //#endregion
            // #region PropertyValidation classes
            class PropertyValidationResult {
                constructor(domComponentId, isInvalid, isWarning, message) {
                    this.domComponentId = domComponentId;
                    this.isInvalid = isInvalid;
                    this.isWarning = isWarning;
                    this.message = message;
                }
                DomComponentId() {
                    return this.domComponentId;
                }
                IsInvalid() {
                    return this.isInvalid;
                }
                IsWarning() {
                    return this.isWarning;
                }
                Message() {
                    return this.message;
                }
            }
            DbResources.PropertyValidationResult = PropertyValidationResult;
            class ResourcePropertyValidationResultCollection {
                constructor(isResourceVisible) {
                    this.isResourceVisible = false;
                    this.propertyValidationResults = [];
                    this.hasError = false;
                    this.hasWarning = false;
                    this.isResourceVisible = isResourceVisible;
                }
                AddPropertyValidationResult(domComponentId, isInvalid, isWarning, message) {
                    this.propertyValidationResults.push(new PropertyValidationResult(domComponentId, isInvalid, isWarning, message));
                    if (isInvalid) {
                        this.hasError = true;
                    }
                    else if (isWarning) {
                        this.hasWarning = true;
                    }
                }
                RemovePropertyValidationResult(domComponentId) {
                    var otherError = false;
                    for (var index = 0; index < this.propertyValidationResults.length; index++) {
                        if (this.propertyValidationResults[index].DomComponentId() == domComponentId) {
                            this.propertyValidationResults.splice(index, 1);
                            index--;
                        }
                        else {
                            otherError = this.propertyValidationResults[index].IsInvalid();
                        }
                    }
                    this.hasError = otherError;
                }
                ValidationResults() {
                    return this.propertyValidationResults;
                }
                HasError() {
                    return this.hasError;
                }
                HasWarning() {
                    return this.hasWarning;
                }
                CreateAlert() {
                    let title = this.hasError ? "Error" : (this.hasWarning ? "Warning" : "Alert");
                    let body = "<div class='validation-message-group'>";
                    let firstId = "";
                    for (let validationIndex = 0; validationIndex < this.propertyValidationResults.length; validationIndex++) {
                        let validationResult = this.propertyValidationResults[validationIndex];
                        if (firstId === "" && validationResult.DomComponentId())
                            firstId = validationResult.DomComponentId();
                        if (validationResult.IsInvalid()) {
                            body += "<span class='validation-icon validation-message-pill'>" + Epic.AppOrchard.Helpers.EncodeText(validationResult.Message()) + "</span>";
                        }
                        else if (validationResult.IsWarning()) {
                            body += "<span class='validation-icon validation-message-pill warning'>" + Epic.AppOrchard.Helpers.EncodeText(validationResult.Message()) + "</span>";
                        }
                        else {
                            body += "<span class='validation-icon validation-message-pill informational'>" + Epic.AppOrchard.Helpers.EncodeText(validationResult.Message()) + "</span>";
                        }
                    }
                    body += "</div>";
                    Epic.AppOrchard.Util.Alert(title, body, $("#" + firstId)[0], true);
                }
                CreateConfirm(onConfirm, onConfirmContext, onClose, onCloseContext, focusOnClose) {
                    let title = this.hasError ? "Error" : (this.hasWarning ? "Warning" : "Alert");
                    let body = "<div class='validation-message-group'>";
                    let firstId = "";
                    for (let validationIndex = 0; validationIndex < this.propertyValidationResults.length; validationIndex++) {
                        let validationResult = this.propertyValidationResults[validationIndex];
                        if (firstId === "" && validationResult.DomComponentId())
                            firstId = validationResult.DomComponentId();
                        if (validationResult.IsInvalid()) {
                            body += "<span class='validation-icon validation-message-pill'>" + Epic.AppOrchard.Helpers.EncodeText(validationResult.Message()) + "</span>";
                        }
                        else if (validationResult.IsWarning()) {
                            body += "<span class='validation-icon validation-message-pill warning'>" + Epic.AppOrchard.Helpers.EncodeText(validationResult.Message()) + "</span>";
                        }
                        else {
                            body += "<span class='validation-icon validation-message-pill informational'>" + Epic.AppOrchard.Helpers.EncodeText(validationResult.Message()) + "</span>";
                        }
                    }
                    body += "</div>";
                    Epic.AppOrchard.Util.Confirm(title, body, onConfirm, onConfirmContext, onClose, onCloseContext, focusOnClose, true, this.hasError || this.hasWarning);
                }
            }
            DbResources.ResourcePropertyValidationResultCollection = ResourcePropertyValidationResultCollection;
            class KeyedResource {
                constructor() {
                    this.GetKeyedResourceIds = () => {
                        throw "GetKeyedResourceIds is not implemented";
                    };
                    this.HasNewRecord = () => {
                        let resourceIds = this.GetKeyedResourceIds.apply(this);
                        if (resourceIds == null) {
                            throw "GetKeyResourceIds() must return non-null";
                        }
                        if (resourceIds.length < 1) {
                            throw "GetKeyResourceIds() must return at least one key id";
                        }
                        for (var x = 0; x < resourceIds.length; x++) {
                            if (resourceIds[x] <= DbResources.NewRecordId) {
                                return true;
                            }
                        }
                        return false;
                    };
                }
                IsNewRecord() {
                    return this.HasNewRecord();
                }
                static GenerateNewRecordId() {
                    return KeyedResource._initialNewRecordId--;
                }
            }
            KeyedResource._initialNewRecordId = DbResources.NewRecordId;
            DbResources.KeyedResource = KeyedResource;
            class SingleKeyedResource extends KeyedResource {
                constructor(id) {
                    super();
                    this.GetKeyedResourceIds = () => {
                        return [this.Id];
                    };
                    if (!id) {
                        id = KeyedResource.GenerateNewRecordId();
                    }
                    this.Id = id;
                }
            }
            DbResources.SingleKeyedResource = SingleKeyedResource;
            class DualKeyedResource extends KeyedResource {
                constructor(id1, id2) {
                    super();
                    this.GetKeyResourceIds = () => {
                        return [this.Id1, this.Id2];
                    };
                    if (!id1) {
                        id1 = KeyedResource.GenerateNewRecordId();
                    }
                    if (!id2) {
                        id2 = KeyedResource.GenerateNewRecordId();
                    }
                    this.Id1 = id1;
                    this.Id2 = id2;
                }
            }
            DbResources.DualKeyedResource = DualKeyedResource;
            class KeyedObservableResource {
                constructor() {
                    this.isLoadOrSave = false;
                    this.collapseOnSaveOrCancel = false;
                    this.CanCollapse = ko.observable(false);
                    this.IsDirty = ko.observable(false);
                    this.IsReadOnly = ko.observable(true);
                    this.IsExpanded = ko.observable(true);
                    this.HasErrors = ko.computed(() => {
                        if (!this.ValidateProperties) {
                            return false;
                        }
                        return this.ValidateProperties.apply(this).HasError();
                    }, this);
                    this.Save = () => {
                        var validationResults = this.ValidateProperties.apply(this);
                        if (validationResults && validationResults.HasError()) {
                            alert("Validation errors have been detected, please clean them up.");
                            return;
                        }
                        if (this.ExecuteAjaxToSaveResource)
                            this.ExecuteAjaxToSaveResource.apply(this);
                        if (this.OnSaved)
                            this.OnSaved.apply(this);
                        if (this.collapseOnSaveOrCancel) {
                            this.IsExpanded(false);
                            this.IsReadOnly(true);
                        }
                        if (this.OnAfterSave != null) {
                            this.OnAfterSave.apply(this);
                        }
                    };
                    this.Edit = () => {
                        if (this.CanCollapse() && !this.IsExpanded()) {
                            this.IsExpanded(true);
                            this.collapseOnSaveOrCancel = true;
                        }
                        this.IsReadOnly(false);
                        var validationResults = this.ValidateProperties.apply(this);
                    };
                    this.ViewOnly = () => {
                        this.Revert();
                        this.IsReadOnly(true);
                    };
                    this.Revert = (val) => {
                        if (val != null) {
                            this.Resource = val;
                        }
                        this.OnRevert.apply(this);
                    };
                    this.Cancel = () => {
                        this.Revert.apply(this);
                        this.IsReadOnly(true);
                        if (this.collapseOnSaveOrCancel) {
                            this.IsExpanded(false);
                            this.collapseOnSaveOrCancel = false;
                        }
                    };
                    this.ExpandOrCollapse = () => {
                        this.IsExpanded(!this.IsExpanded());
                    };
                    this.OnChanged = () => {
                        let x = this.ValidateProperties.apply(this);
                    };
                    this.ValidateProperties = () => {
                        if (!this.OnValidateProperties) {
                            return null;
                        }
                        var validationResults = this.OnValidateProperties.apply(this);
                        var results = validationResults.ValidationResults();
                        for (let index = 0; index < results.length; index++) {
                            var item = results[index];
                            if (item.IsInvalid()) {
                                Epic.AppOrchard.Util.AddErrorClassToElement(item.DomComponentId(), item.Message(), false);
                            }
                            else if (item.IsWarning()) {
                                Epic.AppOrchard.Util.AddErrorClassToElement(item.DomComponentId(), item.Message(), true);
                            }
                            else {
                                Epic.AppOrchard.Util.RemoveErrorClassFromElement(item.DomComponentId(), null);
                            }
                        }
                        return validationResults;
                    };
                }
                GenerateEnumKOArray(enumRef, sourcePropKO) {
                    return Epic.AppOrchard.Util.enumToKoArray(enumRef, sourcePropKO);
                }
                ConvertKOArrayToSimpleArray(arrayOfKOResources) {
                    var result = [];
                    for (var x = 0; x < arrayOfKOResources.length; x++) {
                        let item = arrayOfKOResources[x]();
                        result.push(item.ConvertToJS.apply(item));
                    }
                    return result;
                }
                CreateAndRegisterValidatedKOProperty(defaultValue) {
                    var koProp = ko.observable(defaultValue);
                    koProp.subscribe(() => {
                        this.OnChanged.apply(this);
                    }, this);
                    return koProp;
                }
                CreateAndRegisterValidatedKOArrayProperty() {
                    var koProp = ko.observableArray([]);
                    koProp.subscribe(() => {
                        this.OnChanged.apply(this);
                    }, this);
                    return koProp;
                }
            }
            DbResources.KeyedObservableResource = KeyedObservableResource;
            class SelectionType {
                constructor(id, name, selected = false) {
                    this.Id = id;
                    this.Name = name;
                    this.Selected = selected;
                }
            }
            DbResources.SelectionType = SelectionType;
            class SelectionTypeKO {
                constructor(selectType) {
                    this.Id = ko.observable(0);
                    this.Name = ko.observable("");
                    this.Selected = ko.observable(false);
                    this.Id(selectType.Id);
                    this.Name(selectType.Name);
                    this.Selected(selectType.Selected);
                }
            }
            SelectionTypeKO.GetSelected = (selectionOptions) => {
                if (selectionOptions == null) {
                    return [];
                }
                let selected = [];
                for (let versionIndex = 0; versionIndex < selectionOptions.length; versionIndex++) {
                    if (selectionOptions[versionIndex].Selected()) {
                        selected.push(selectionOptions[versionIndex]);
                    }
                }
                return selected;
            };
            SelectionTypeKO.GetSelectedIds = (selectionOptions) => {
                if (selectionOptions == null) {
                    return [];
                }
                let selected = [];
                for (let versionIndex = 0; versionIndex < selectionOptions.length; versionIndex++) {
                    if (selectionOptions[versionIndex].Selected()) {
                        selected.push(selectionOptions[versionIndex].Id());
                    }
                }
                return selected;
            };
            DbResources.SelectionTypeKO = SelectionTypeKO;
            class Tuple {
            }
            DbResources.Tuple = Tuple;
            class VersionDownloadStatus {
                constructor(id, name, vendorApproved, licensedBy, licensedOn) {
                    this.Id = id;
                    this.Name = name;
                    this.VendorApproved = vendorApproved;
                    this.LicensedBy = licensedBy;
                    this.LicensedOn = licensedOn;
                }
            }
            DbResources.VersionDownloadStatus = VersionDownloadStatus;
            class VersionDownloadStatusKO {
                constructor(data) {
                    this.Id = ko.observable(0);
                    this.Name = ko.observable("");
                    this.VendorApproved = ko.observable(-1);
                    this.LicensedBy = ko.observable("");
                    this.LicensedOn = ko.observable("");
                    this.Id(data.Id);
                    this.Name(data.Name);
                    this.VendorApproved(data.VendorApproved);
                    this.LicensedBy(data.LicensedBy);
                    this.LicensedOn(data.LicensedOn);
                }
            }
            DbResources.VersionDownloadStatusKO = VersionDownloadStatusKO;
            class SingleKeyedObservableResource extends KeyedObservableResource {
                constructor(resource) {
                    super();
                    this.Id = ko.observable(DbResources.NewRecordId);
                    if (!resource) {
                        throw "Resource is null";
                    }
                    this.Resource = resource;
                    this.Id(resource.Id);
                }
            }
            DbResources.SingleKeyedObservableResource = SingleKeyedObservableResource;
            class DualKeyedObservableResource extends KeyedObservableResource {
                constructor(resource) {
                    super();
                    this.Id1 = ko.observable(DbResources.NewRecordId);
                    this.Id2 = ko.observable(DbResources.NewRecordId);
                    if (!resource) {
                        throw "Resource is null";
                    }
                    if (!resource) {
                        throw "Resource must not be null";
                    }
                    this.Resource = resource;
                    this.Id1(resource.Id1);
                    this.Id2(resource.Id2);
                }
            }
            DbResources.DualKeyedObservableResource = DualKeyedObservableResource;
            class Questionnaire_Question extends SingleKeyedResource {
                constructor(...args) {
                    super(...args);
                    this.Text = "";
                    this.ResponseText = "";
                    this.Indent = false;
                    this.OrderNumber = 0;
                    this.Type = DbResources.QuestionnaireQuestionType.Freetext;
                    this.Questionnaire = null;
                }
            }
            DbResources.Questionnaire_Question = Questionnaire_Question;
            class Questionnaire_QuestionKO extends SingleKeyedObservableResource {
                constructor(question, questionnaire) {
                    super(question);
                    this.Id = super.CreateAndRegisterValidatedKOProperty(0);
                    this.Text = super.CreateAndRegisterValidatedKOProperty("");
                    this.ResponseText = super.CreateAndRegisterValidatedKOProperty("");
                    this.Indent = super.CreateAndRegisterValidatedKOProperty(false);
                    this.OrderNumber = super.CreateAndRegisterValidatedKOProperty(0);
                    this.Type = super.CreateAndRegisterValidatedKOProperty(DbResources.QuestionnaireQuestionType.Freetext);
                    this.Questionnaire = super.CreateAndRegisterValidatedKOProperty(null);
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Text: this.Text(),
                            ResponseText: this.ResponseText(),
                            OrderNumber: this.OrderNumber(),
                            Type: this.Type(),
                            Indent: this.Indent(),
                        };
                    };
                    this.ConvertToJSList = () => {
                        return {
                            Id: this.Id(),
                            Text: this.Text(),
                            ResponseText: this.ResponseText(),
                            OrderNumber: this.OrderNumber(),
                            Type: this.Type(),
                            Indent: this.Indent(),
                            Questionnaire: this.Questionnaire(),
                        };
                    };
                    this.CompareOrder = (left, right) => {
                        return left().OrderNumber() - right().OrderNumber();
                    };
                    if (question == null) {
                        return;
                    }
                    this.Id(question.Id);
                    this.Text(question.Text);
                    this.ResponseText(question.ResponseText);
                    this.Indent(question.Indent);
                    this.OrderNumber(question.OrderNumber);
                    this.Type(question.Type);
                    this.Questionnaire(questionnaire);
                    question.Questionnaire = question.Questionnaire || questionnaire;
                }
                ;
            }
            DbResources.Questionnaire_QuestionKO = Questionnaire_QuestionKO;
            class Questionnaire_Category extends SingleKeyedResource {
                constructor(...args) {
                    super(...args);
                    this.Title = "";
                    this.Description = "";
                    this.Questions = [];
                }
            }
            DbResources.Questionnaire_Category = Questionnaire_Category;
            class Questionnaire_CategoryKO extends SingleKeyedObservableResource {
                constructor(category, questionnaire) {
                    super(category);
                    this.Id = super.CreateAndRegisterValidatedKOProperty(0);
                    this.Title = super.CreateAndRegisterValidatedKOProperty("");
                    this.Description = super.CreateAndRegisterValidatedKOProperty("");
                    this.Questions = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.CompareOrder = (left, right) => {
                        return left().OrderNumber() - right().OrderNumber();
                    };
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Title: this.Title(),
                            Description: this.Description(),
                            Questions: this.Questions()
                        };
                    };
                    this.ConvertToJSList = () => {
                        return {
                            Id: this.Id(),
                            Title: this.Title(),
                            Description: this.Description(),
                            Questions: super.ConvertKOArrayToSimpleArray(this.Questions())
                        };
                    };
                    if (category == null) {
                        return;
                    }
                    this.Id(category.Id ? category.Id : -1);
                    this.Title(category.Title);
                    this.Description(category.Description);
                    if (category.Questions) {
                        for (let x = 0; x < category.Questions.length; x++) {
                            let question = category.Questions[x];
                            let questionKO = new Questionnaire_QuestionKO(question, questionnaire);
                            this.Questions.push(ko.observable(questionKO));
                        }
                        this.Questions.sort(this.CompareOrder);
                    }
                }
            }
            DbResources.Questionnaire_CategoryKO = Questionnaire_CategoryKO;
            class QuestionnaireKO extends SingleKeyedObservableResource {
                constructor(questionnaire) {
                    super(questionnaire);
                    this.VersionId = super.CreateAndRegisterValidatedKOProperty(0);
                    this.VersionName = super.CreateAndRegisterValidatedKOProperty("");
                    this.Categories = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.OrganizationName = super.CreateAndRegisterValidatedKOProperty("");
                    this.ApplicationName = super.CreateAndRegisterValidatedKOProperty("");
                    this.ShowAllQuestionsToAdmin = super.CreateAndRegisterValidatedKOProperty(false);
                    this.Active = super.CreateAndRegisterValidatedKOProperty(false);
                    this.LastEditDate = super.CreateAndRegisterValidatedKOProperty("");
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            VersionId: this.VersionId(),
                            Categories: super.ConvertKOArrayToSimpleArray(this.Categories()),
                            OrganizationName: this.OrganizationName(),
                            ApplicationName: this.ApplicationName(),
                        };
                    };
                    if (questionnaire == null) {
                        return;
                    }
                    QuestionnaireKO.Populate(this, questionnaire);
                }
                static Populate(questionnaire, data) {
                    questionnaire.Id(data.Id);
                    questionnaire.VersionId(data.VersionId);
                    questionnaire.VersionName(data.VersionName);
                    questionnaire.LastEditDate((new Date(data.LastEditDate)).toLocaleDateString());
                    if (data.Categories) {
                        for (let x = 0; x < data.Categories.length; x++) {
                            let category = data.Categories[x];
                            let categoryKO = new Questionnaire_CategoryKO(category, questionnaire);
                            categoryKO.CanCollapse(true);
                            categoryKO.IsExpanded(false);
                            questionnaire.Categories.push(ko.observable(categoryKO));
                        }
                    }
                }
            }
            DbResources.QuestionnaireKO = QuestionnaireKO;
            class Questionnaire extends SingleKeyedResource {
                constructor(...args) {
                    super(...args);
                    this.VersionId = 0;
                    this.VersionName = "";
                    this.LastEditDate = "";
                    this.Categories = [];
                }
            }
            DbResources.Questionnaire = Questionnaire;
            class Organization extends SingleKeyedResource {
                constructor(id, programLevel, uscdiProgramLevel, name, webSite, address, internationaladdress, city, state, zip, country, incorporationState, products, affiliatedCustomers, dateofcreation, approvalDate, comments, empUserName, empUserPassword, kitUserName, kitUserPassword, isSherlockActivated, disabled, coiExpirationDate, displayName, organizationStatus, uscdiOrganizationStatus, authorizedUsers, userTotalCount, aoUserCount, applications, regions, hasParentRegion, governanceMessage, governanceUrl, epicVersion, allowSigningToolboxAgreement) {
                    super(id);
                    this.EpicCommunityMember_Id = 0;
                    this.ProgramLevel = ProgramLevel.Undefined;
                    this.USCDIProgramLevel = ProgramLevel.Undefined;
                    this.Name = "";
                    this.WebSite = "";
                    this.Address = "";
                    this.InternationalAddress = "";
                    this.City = "";
                    this.State = "";
                    this.Zip = "";
                    this.Country = "";
                    this.IncorporationState = "";
                    this.Products = "";
                    this.AffiliatedCustomers = "";
                    this.DateOfCreation = "";
                    this.ApprovalDate = "";
                    this.Comments = "";
                    this.EmpUserName = "";
                    this.EmpUserPassword = "";
                    this.KitUserName = "";
                    this.KitUserPassword = "";
                    this.IsSherlockActivated = false;
                    this.Disabled = false;
                    this.COIExpirationDate = "";
                    this.DisplayName = "";
                    this.OrganizationStatus = OrganizationStatus.Undefined;
                    this.USCDIOrganizationStatus = OrganizationStatus.Undefined;
                    this.AuthorizedUsers = [];
                    this.UserTotalCount = 0;
                    this.AOUserCount = 0;
                    this.Applications = [];
                    this.Regions = [];
                    this.HasParentRegion = false;
                    this.GovernanceMessage = "";
                    this.GovernanceUrl = "";
                    this.EpicVersion = "";
                    this.AllowSigningToolboxAgreement = false;
                    if (programLevel)
                        this.ProgramLevel = programLevel;
                    if (uscdiProgramLevel)
                        this.USCDIProgramLevel = uscdiProgramLevel;
                    if (name)
                        this.Name = name;
                    if (webSite)
                        this.WebSite = webSite;
                    if (address)
                        this.Address = address;
                    if (internationaladdress)
                        this.InternationalAddress = internationaladdress;
                    if (city)
                        this.City = city;
                    if (state)
                        this.State = state;
                    if (zip)
                        this.Zip = zip;
                    if (country)
                        this.Country = country;
                    if (incorporationState)
                        this.IncorporationState = incorporationState;
                    if (products)
                        this.Products = products;
                    if (affiliatedCustomers)
                        this.AffiliatedCustomers = affiliatedCustomers;
                    if (dateofcreation)
                        this.DateOfCreation = dateofcreation;
                    if (approvalDate)
                        this.ApprovalDate = approvalDate;
                    if (comments)
                        this.Comments = comments;
                    if (empUserName)
                        this.EmpUserName = empUserName;
                    if (empUserPassword)
                        this.EmpUserPassword = empUserPassword;
                    if (kitUserName)
                        this.KitUserName = kitUserName;
                    if (kitUserPassword)
                        this.KitUserPassword = kitUserPassword;
                    if (isSherlockActivated)
                        this.IsSherlockActivated = isSherlockActivated;
                    if (disabled)
                        this.Disabled = disabled;
                    if (coiExpirationDate)
                        this.COIExpirationDate = coiExpirationDate;
                    if (displayName)
                        this.DisplayName = displayName;
                    if (organizationStatus)
                        this.OrganizationStatus = organizationStatus;
                    if (uscdiOrganizationStatus)
                        this.USCDIOrganizationStatus = uscdiOrganizationStatus;
                    if (hasParentRegion)
                        this.HasParentRegion = hasParentRegion;
                    if (governanceMessage)
                        this.GovernanceMessage = governanceMessage;
                    if (governanceUrl)
                        this.GovernanceUrl = governanceUrl;
                    if (userTotalCount)
                        this.UserTotalCount = userTotalCount;
                    if (aoUserCount)
                        this.AOUserCount = aoUserCount;
                    if (epicVersion)
                        this.EpicVersion = epicVersion;
                    if (allowSigningToolboxAgreement)
                        this.AllowSigningToolboxAgreement = allowSigningToolboxAgreement;
                    if (authorizedUsers) {
                        this.AuthorizedUsers = authorizedUsers;
                    }
                    if (applications) {
                        this.Applications = applications;
                    }
                    if (regions) {
                        this.Regions = regions;
                    }
                }
            }
            DbResources.Organization = Organization;
            class OrganizationKO extends SingleKeyedObservableResource {
                constructor(organization) {
                    super(organization);
                    this.EpicCommunityMember_Id = super.CreateAndRegisterValidatedKOProperty(0);
                    this.ProgramLevel = super.CreateAndRegisterValidatedKOProperty(ProgramLevel.Undefined);
                    this.USCDIProgramLevel = super.CreateAndRegisterValidatedKOProperty(ProgramLevel.Undefined);
                    this.Name = super.CreateAndRegisterValidatedKOProperty("");
                    this.WebSite = super.CreateAndRegisterValidatedKOProperty("");
                    this.Address = super.CreateAndRegisterValidatedKOProperty("");
                    this.InternationalAddress = super.CreateAndRegisterValidatedKOProperty("");
                    this.City = super.CreateAndRegisterValidatedKOProperty("");
                    this.State = super.CreateAndRegisterValidatedKOProperty("");
                    this.Zip = super.CreateAndRegisterValidatedKOProperty("");
                    this.Country = super.CreateAndRegisterValidatedKOProperty("");
                    this.IncorporationState = super.CreateAndRegisterValidatedKOProperty("");
                    this.Products = super.CreateAndRegisterValidatedKOProperty("");
                    this.AffiliatedCustomers = super.CreateAndRegisterValidatedKOProperty("");
                    this.Comments = super.CreateAndRegisterValidatedKOProperty("");
                    this.EmpUserName = super.CreateAndRegisterValidatedKOProperty("");
                    this.EmpUserPassword = super.CreateAndRegisterValidatedKOProperty("");
                    this.KitUserName = super.CreateAndRegisterValidatedKOProperty("");
                    this.KitUserPassword = super.CreateAndRegisterValidatedKOProperty("");
                    this.IsSherlockActivated = super.CreateAndRegisterValidatedKOProperty(false);
                    this.Disabled = super.CreateAndRegisterValidatedKOProperty(false);
                    this.COIExpirationDate = super.CreateAndRegisterValidatedKOProperty("");
                    this.DisplayName = super.CreateAndRegisterValidatedKOProperty("");
                    this.OrganizationStatus = super.CreateAndRegisterValidatedKOProperty(OrganizationStatus.Undefined);
                    this.USCDIOrganizationStatus = super.CreateAndRegisterValidatedKOProperty(OrganizationStatus.Undefined);
                    this.DateOfCreation = super.CreateAndRegisterValidatedKOProperty("");
                    this.ApprovalDate = super.CreateAndRegisterValidatedKOProperty("");
                    this.AuthorizedUsers = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.Applications = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.Visible = super.CreateAndRegisterValidatedKOProperty(true);
                    this.ManualStatusEdit = super.CreateAndRegisterValidatedKOProperty(false);
                    this.ManualProgramLevelEdit = super.CreateAndRegisterValidatedKOProperty(false);
                    this.SaveSuccess = super.CreateAndRegisterValidatedKOProperty(false);
                    this.SaveFailure = super.CreateAndRegisterValidatedKOProperty(false);
                    this.SaveFailureError = super.CreateAndRegisterValidatedKOProperty("");
                    this.Regions = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.HasParentRegion = super.CreateAndRegisterValidatedKOProperty(false);
                    this.BindableProgramLevels = null;
                    this.BindableStatus = null;
                    this.ProgramLevelName = null;
                    this.USCDIProgramLevelName = null;
                    this.IsEnrolledInUSCDI = null;
                    this.IsOnlyInUSCDI = null;
                    this.EditStatus = super.CreateAndRegisterValidatedKOProperty(false);
                    this.SlgName = super.CreateAndRegisterValidatedKOProperty("");
                    this.IsStatsAvailable = super.CreateAndRegisterValidatedKOProperty(false);
                    this.GovernanceMessage = super.CreateAndRegisterValidatedKOProperty("");
                    this.GovernanceUrl = super.CreateAndRegisterValidatedKOProperty("");
                    this.EpicVersion = super.CreateAndRegisterValidatedKOProperty("");
                    this.AllowSigningToolboxAgreement = super.CreateAndRegisterValidatedKOProperty(false);
                    this.UserPageSize = 20;
                    this.UserCurrentPage = ko.observable(0);
                    this.UserTotalCount = ko.observable(0);
                    this.UserSearchText = ko.observable("");
                    this.AOUserCount = ko.observable(0);
                    this.UserTotalPages = ko.computed(() => {
                        if (this.UserTotalCount && this.UserTotalCount() && this.UserTotalCount() > 0) {
                            var pages = Math.floor((this.UserTotalCount() - 1) / this.UserPageSize);
                            return pages;
                        }
                        return 0;
                    });
                    this.UserFilteredText = ko.computed(() => {
                        if (!this.UserTotalCount() || this.UserTotalCount() == 0) {
                            return "No users found";
                        }
                        else if (this.UserTotalCount() && this.UserTotalCount() == 1) {
                            return this.UserTotalCount() + " user found";
                        }
                        else {
                            return this.UserTotalCount() + " users found";
                        }
                    });
                    this.IsCommunityMember = ko.computed(() => {
                        return this.ProgramLevel() == DbResources.ProgramLevel.EpicCommunityMember || this.USCDIProgramLevel() == DbResources.ProgramLevel.EpicCommunityMember;
                    });
                    this.ExecuteAjaxToSaveResource = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "Organization/Single", false, this.ConvertToJS(), (data, textStatus, jqXHR) => {
                            this.Id(data.Id);
                            this.SaveSuccess(true);
                            this.SaveFailure(false);
                            this.AuthorizedUsers.removeAll();
                            this.UserTotalCount(data.UserTotalCount);
                            if (data.AuthorizedUsers) {
                                for (let x = 0; x < data.AuthorizedUsers.length; x++) {
                                    let user = data.AuthorizedUsers[x];
                                    let userKO = new AuthorizedUserKO(user);
                                    userKO.ProgramLevel(this.ProgramLevel());
                                    userKO.USCDIProgramLevel(this.USCDIProgramLevel());
                                    userKO.CanCollapse(true);
                                    userKO.IsExpanded(false);
                                    this.AuthorizedUsers.push(ko.observable(userKO));
                                }
                            }
                            if (data.Error) {
                                Epic.AppOrchard.Util.Alert("Warning", "Parts of the organization record were saved successfully but an error occurred that prevented saving the whole record: " + data.Error);
                            }
                            else {
                                Epic.AppOrchard.Util.Alert("Success", "Organization saved successfully. ");
                                this.IsExpanded(false);
                                this.IsReadOnly(true);
                            }
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "Organization/Single");
                            this.SaveFailure(true);
                            this.SaveSuccess(false);
                            this.SaveFailureError(errorThrown);
                            Epic.AppOrchard.Util.Alert("Error", "The saving process ran into a problem: " + errorThrown);
                        }, 30000, false, this);
                    };
                    this.OnValidateProperties = () => {
                        let result = new ResourcePropertyValidationResultCollection(!this.CanCollapse() || !this.IsReadOnly());
                        // add logic for verification
                        result.AddPropertyValidationResult("txtOrganizationWebSite" + this.Id(), (!Epic.AppOrchard.Util.IsNullOrEmpty(this.WebSite()) && (!((/^([a-z][a-z0-9+.-]*):(?:\/\/((?:(?=((?:[a-z0-9-._~!$&'()*+,;=:]|%[0-9A-F]{2})*))(\3)@@)?(?=(\[[0-9A-F:.]{2,}\]|(?:[a-z0-9-._~!$&'()*+,;=]|%[0-9A-F]{2})*))\5(?::(?=(\d*))\6)?)(\/(?=((?:[a-z0-9-._~!$&'()*+,;=:@@\/]|%[0-9A-F]{2})*))\8)?|(\/?(?!\/)(?=((?:[a-z0-9-._~!$&'()*+,;=:@@\/]|%[0-9A-F]{2})*))\10)?)(?:\?(?=((?:[a-z0-9-._~!$&'()*+,;=:@@\/?]|%[0-9A-F]{2})*))\11)?(?:#(?=((?:[a-z0-9-._~!$&'()*+,;=:@@\/?]|%[0-9A-F]{2})*))\12)?$/i.test(this.WebSite())) ||
                            (/^((http[s]?|ftp):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/i.test(this.WebSite())) ||
                            (/^(http\:\/\/|https\:\/\/)?([a-z0-9][a-z0-9\-]*\.)+[a-z0-9][a-z0-9\-]*$/i.test(this.WebSite()))))), false, "A valid web site is required.");
                        result.AddPropertyValidationResult("txtCOIExpirationDate" + this.Id(), (!Epic.AppOrchard.Util.IsNullOrEmpty(this.COIExpirationDate()) &&
                            (!(/^(?:(?:(?:0?[13578]|1[02])(\/)31)\1|(?:(?:0?[1,3-9]|1[0-2])(\/)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))(\/)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$/i.test(this.COIExpirationDate())))), false, "Enter a date in the format MM/DD/YYYY");
                        if (this.ProgramLevel() == Epic.AppOrchard.DbResources.ProgramLevel.EpicCommunityMember) {
                            $("#txtOrganizationCountry" + this.Id()).removeClass("input-validation-error");
                            $("#txtOrganizationAddress" + this.Id()).removeClass("input-validation-error");
                            $("#txtOrganizationCity" + this.Id()).removeClass("input-validation-error");
                            $("#txtOrganizationZip" + this.Id()).removeClass("input-validation-error");
                            $("#txtOrganizationState" + this.Id()).removeClass("input-validation-error");
                            $("#txtOrganizationIncorporationState" + this.Id()).removeClass("input-validation-error");
                            $("#txtOrganizationInternationalAddress" + this.Id()).removeClass("input-validation-error");
                        }
                        else {
                            result.AddPropertyValidationResult("txtOrganizationCountry" + this.Id(), (Epic.AppOrchard.Util.IsNullOrEmpty(this.Country()) || !(/^[-'\., a-zA-Z0-9\u00E0-\u00FC]+$/i.test(this.Country()))), false, "A valid country is required.");
                            if (this.Country() == "United States") {
                                result.AddPropertyValidationResult("txtOrganizationAddress" + this.Id(), (Epic.AppOrchard.Util.IsNullOrEmpty(this.Address()) || !(/^[-#'\., a-zA-Z0-9\u00E0-\u00FC]+$/i.test(this.Address()))), false, "A valid address is required.");
                                result.AddPropertyValidationResult("txtOrganizationCity" + this.Id(), (Epic.AppOrchard.Util.IsNullOrEmpty(this.City()) || !(/^[-'@@#!%&*\., a-zA-Z0-9\u00E0-\u00FC]+$/i.test(this.City()))), false, "A valid city is required.");
                                result.AddPropertyValidationResult("txtOrganizationState" + this.Id(), (Epic.AppOrchard.Util.IsNullOrEmpty(this.State()) || !(/^[-'\., a-zA-Z0-9\u00E0-\u00FC]+$/i.test(this.State()))), false, "A valid state is required.");
                                result.AddPropertyValidationResult("txtOrganizationZip" + this.Id(), (Epic.AppOrchard.Util.IsNullOrEmpty(this.Zip()) || !(/^[- 0-9]+$/i.test(this.Zip()))), false, "A valid ZIP code is required.");
                                result.AddPropertyValidationResult("txtOrganizationIncorporationState" + this.Id(), !(/^[-'\., a-zA-Z0-9\u00E0-\u00FC]*$/i.test(this.IncorporationState())), false, "Incorporation state cannot be invalid.");
                                $("#txtOrganizationInternationalAddress" + this.Id()).removeClass("input-validation-error");
                            }
                            else {
                                result.AddPropertyValidationResult("txtOrganizationInternationalAddress" + this.Id(), (Epic.AppOrchard.Util.IsNullOrEmpty(this.InternationalAddress())), false, "A valid address is required.");
                                $("#txtOrganizationAddress" + this.Id()).removeClass("input-validation-error");
                                $("#txtOrganizationCity" + this.Id()).removeClass("input-validation-error");
                                $("#txtOrganizationZip" + this.Id()).removeClass("input-validation-error");
                                $("#txtOrganizationState" + this.Id()).removeClass("input-validation-error");
                                $("#txtOrganizationIncorporationState" + this.Id()).removeClass("input-validation-error");
                            }
                        }
                        if (this.Resource.OrganizationStatus != this.OrganizationStatus() && this.OrganizationStatus() == OrganizationStatus.ProgramLevelApproved) {
                            result.AddPropertyValidationResult("txtEpicCommunityMember_Id" + this.Id(), (this.EpicCommunityMember_Id() <= 0), false, "A valid SLG is required.");
                        }
                        return result;
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.EpicCommunityMember_Id = this.EpicCommunityMember_Id();
                        this.Resource.ProgramLevel = this.ProgramLevel();
                        this.Resource.USCDIProgramLevel = this.USCDIProgramLevel();
                        this.Resource.Name = this.Name();
                        this.Resource.WebSite = this.WebSite();
                        this.Resource.Address = this.Address();
                        this.Resource.InternationalAddress = this.InternationalAddress();
                        this.Resource.City = this.City();
                        this.Resource.State = this.State();
                        this.Resource.Zip = this.Zip();
                        this.Resource.Country = this.Country();
                        this.Resource.IncorporationState = this.IncorporationState();
                        this.Resource.Products = this.Products();
                        this.Resource.AffiliatedCustomers = this.AffiliatedCustomers();
                        this.Resource.Comments = this.Comments();
                        this.Resource.EmpUserName = this.EmpUserName();
                        this.Resource.EmpUserPassword = this.EmpUserPassword();
                        this.Resource.KitUserName = this.KitUserName();
                        this.Resource.KitUserPassword = this.KitUserPassword();
                        this.Resource.IsSherlockActivated = this.IsSherlockActivated();
                        this.Resource.Disabled = this.Disabled();
                        this.Resource.COIExpirationDate = this.COIExpirationDate();
                        this.Resource.DisplayName = this.DisplayName();
                        this.Resource.OrganizationStatus = this.OrganizationStatus();
                        this.Resource.USCDIOrganizationStatus = this.USCDIOrganizationStatus();
                        this.Resource.GovernanceMessage = this.GovernanceMessage();
                        this.Resource.GovernanceUrl = this.GovernanceUrl();
                        this.Resource.AllowSigningToolboxAgreement = this.AllowSigningToolboxAgreement();
                        this.Resource.AuthorizedUsers = [];
                        for (let x = 0; x < this.AuthorizedUsers().length; x++) {
                            this.Resource.AuthorizedUsers.push(this.AuthorizedUsers()[x]().ConvertToJS());
                        }
                        this.Id.notifySubscribers();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.EpicCommunityMember_Id(this.Resource.EpicCommunityMember_Id);
                        this.ProgramLevel(this.Resource.ProgramLevel);
                        this.USCDIProgramLevel(this.Resource.USCDIProgramLevel);
                        this.Name(this.Resource.Name);
                        this.WebSite(this.Resource.WebSite);
                        this.Address(this.Resource.Address);
                        this.InternationalAddress(this.Resource.InternationalAddress);
                        this.City(this.Resource.City);
                        this.State(this.Resource.State);
                        this.Zip(this.Resource.Zip);
                        this.Country(this.Resource.Country);
                        this.IncorporationState(this.Resource.IncorporationState);
                        this.Products(this.Resource.Products);
                        this.AffiliatedCustomers(this.Resource.AffiliatedCustomers);
                        this.Comments(this.Resource.Comments);
                        this.EmpUserName(this.Resource.EmpUserName);
                        this.EmpUserPassword(this.Resource.EmpUserPassword);
                        this.KitUserName(this.Resource.KitUserName);
                        this.KitUserPassword(this.Resource.KitUserPassword);
                        this.IsSherlockActivated(this.Resource.IsSherlockActivated);
                        this.Disabled(this.Resource.Disabled);
                        this.COIExpirationDate(this.Resource.COIExpirationDate);
                        this.DisplayName(this.Resource.DisplayName);
                        this.OrganizationStatus(this.Resource.OrganizationStatus);
                        this.USCDIOrganizationStatus(this.Resource.USCDIOrganizationStatus);
                        this.GovernanceMessage(this.Resource.GovernanceMessage);
                        this.GovernanceUrl(this.Resource.GovernanceUrl);
                        this.UserTotalCount(this.Resource.UserTotalCount);
                        this.AOUserCount(this.Resource.AOUserCount);
                        this.EpicVersion(this.Resource.EpicVersion);
                        this.AllowSigningToolboxAgreement(this.Resource.AllowSigningToolboxAgreement);
                    };
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            EpicCommunityMember_Id: this.EpicCommunityMember_Id(),
                            ProgramLevel: this.ProgramLevel(),
                            USCDIProgramLevel: this.USCDIProgramLevel(),
                            Name: this.Name(),
                            WebSite: this.WebSite(),
                            Address: this.Address(),
                            InternationalAddress: this.InternationalAddress(),
                            City: this.City(),
                            State: this.State(),
                            Zip: this.Zip(),
                            Country: this.Country(),
                            IncorporationState: this.IncorporationState(),
                            Products: this.Products(),
                            AffiliatedCustomers: this.AffiliatedCustomers(),
                            Comments: this.Comments(),
                            EmpUserName: this.EmpUserName(),
                            EmpUserPassword: this.EmpUserPassword(),
                            KitUserName: this.KitUserName(),
                            KitUserPassword: this.KitUserPassword(),
                            IsSherlockActivated: this.IsSherlockActivated(),
                            Disabled: this.Disabled(),
                            COIExpirationDate: this.COIExpirationDate(),
                            DisplayName: this.DisplayName(),
                            OrganizationStatus: this.OrganizationStatus(),
                            USCDIOrganizationStatus: this.USCDIOrganizationStatus(),
                            AuthorizedUsers: super.ConvertKOArrayToSimpleArray(this.AuthorizedUsers()),
                            GovernanceMessage: this.GovernanceMessage(),
                            GovernanceUrl: this.GovernanceUrl(),
                            AllowSigningToolboxAgreement: this.AllowSigningToolboxAgreement(),
                        };
                    };
                    this.ChangeUserOrganization = (authUser) => {
                        $('#directEmployeeModal' + authUser.Id()).modal('hide');
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "AuthorizedUser/UpdateUserOrganization", false, { authUser: authUser.ConvertToJS(), directEmployeeOrg: authUser.DirectEmployeeOrg() }, (data, textStatus, jqXHR) => {
                            if (data.Success) {
                                this.RemoveUser(authUser, null, null);
                                Epic.AppOrchard.Util.Alert("Success", "User's organization successfully updated.");
                            }
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "AuthorizedUser/UpdateUserOrganization");
                        }, 3000, true, this);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (!this.Resource) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.EpicCommunityMember_Id() != this.Resource.EpicCommunityMember_Id) ||
                            (this.ProgramLevel() != this.Resource.ProgramLevel) ||
                            (this.USCDIProgramLevel() != this.Resource.USCDIProgramLevel) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.WebSite() != this.Resource.WebSite) ||
                            (this.Address() != this.Resource.Address) ||
                            (this.InternationalAddress() != this.Resource.InternationalAddress) ||
                            (this.City() != this.Resource.City) ||
                            (this.State() != this.Resource.State) ||
                            (this.Zip() != this.Resource.Zip) ||
                            (this.Country() != this.Resource.Country) ||
                            (this.IncorporationState() != this.Resource.IncorporationState) ||
                            (this.Products() != this.Resource.Products) ||
                            (this.AffiliatedCustomers() != this.Resource.AffiliatedCustomers) ||
                            (this.Comments() != this.Resource.Comments) ||
                            (this.EmpUserName() != this.Resource.EmpUserName) ||
                            (this.EmpUserPassword() != this.Resource.EmpUserPassword) ||
                            (this.KitUserName() != this.Resource.KitUserName) ||
                            (this.KitUserPassword() != this.Resource.KitUserPassword) ||
                            (this.IsSherlockActivated() != this.Resource.IsSherlockActivated) ||
                            (this.Disabled() != this.Resource.Disabled) ||
                            (this.COIExpirationDate() != this.Resource.COIExpirationDate) ||
                            (this.DisplayName() != this.Resource.DisplayName) ||
                            (this.OrganizationStatus() != this.Resource.OrganizationStatus) ||
                            (this.USCDIOrganizationStatus() != this.Resource.USCDIOrganizationStatus) ||
                            (this.GovernanceMessage() != this.Resource.GovernanceMessage) ||
                            (this.GovernanceUrl() != this.Resource.GovernanceUrl) ||
                            (this.AllowSigningToolboxAgreement() != this.Resource.AllowSigningToolboxAgreement)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.ViewOnlyOrg = () => {
                        this.ViewOnly();
                        for (let user of this.AuthorizedUsers()) {
                            user().ViewOnly();
                            user().IsExpanded(false);
                        }
                    };
                    this.AddUser = () => {
                        let userKO = new AuthorizedUserKO(new AuthorizedUser(null, this.Id(), UserAccountType.VendorDeveloper));
                        userKO.ProgramLevel(this.ProgramLevel());
                        userKO.USCDIProgramLevel(this.USCDIProgramLevel());
                        this.AuthorizedUsers.push(ko.observable(userKO));
                        this.UserTotalCount(this.UserTotalCount() + 1);
                        userKO.CanCollapse(true);
                        userKO.IsExpanded(true);
                        userKO.NewUser(true);
                        userKO.Edit();
                    };
                    this.RemoveUser = (o, r, t) => {
                        for (let x = 0; x < this.AuthorizedUsers().length; x++) {
                            if (this.AuthorizedUsers()[x]().Id() == o.Id()) {
                                this.AuthorizedUsers.remove(this.AuthorizedUsers()[x]);
                                this.UserTotalCount(this.UserTotalCount() - 1);
                                break;
                            }
                        }
                    };
                    this.SaveUser = (user) => {
                        if (user == null) {
                            return;
                        }
                        let model = this;
                        user.OnAfterSave = function () {
                            model.LoadUsers();
                        };
                        user.Save();
                    };
                    this.ApproveStatusSave = () => {
                        this.UpdateStatus();
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "Organization/UpdateStatus", false, this.ConvertToJS(), (data, textStatus, jqXHR) => {
                            this.SaveSuccess(true);
                            this.SaveFailure(false);
                            this.AuthorizedUsers.removeAll();
                            this.UserTotalCount(data.UserTotalCount);
                            if (data.AuthorizedUsers) {
                                for (let x = 0; x < data.AuthorizedUsers.length; x++) {
                                    let user = data.AuthorizedUsers[x];
                                    let userKO = new AuthorizedUserKO(user);
                                    userKO.ProgramLevel(this.ProgramLevel());
                                    userKO.USCDIProgramLevel(this.USCDIProgramLevel());
                                    userKO.CanCollapse(true);
                                    userKO.IsExpanded(false);
                                    this.AuthorizedUsers.push(ko.observable(userKO));
                                }
                            }
                            Epic.AppOrchard.Util.Alert("Success", "Organization and user status updated successfully. " + data.Error);
                            this.IsExpanded(false);
                            this.IsReadOnly(true);
                            this.Visible(false);
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "Organization/UpdateStatus");
                            this.SaveFailure(true);
                            this.SaveSuccess(false);
                            this.SaveFailureError(errorThrown);
                            Epic.AppOrchard.Util.Alert("Error", "The saving process ran into a problem: " + errorThrown);
                        }, 30000, false, this);
                    };
                    this.UserClearClicked = () => {
                        this.UserSearchText("");
                        this.UserSearchClicked();
                    };
                    this.UserSearchClicked = () => {
                        this.UserCurrentPage(0);
                        this.LoadUsers();
                    };
                    this.UserMoveFirst = () => {
                        this.UserCurrentPage(0);
                        this.LoadUsers();
                    };
                    this.UserMovePrevious = () => {
                        this.UserCurrentPage(this.UserCurrentPage() - 1);
                        this.LoadUsers();
                    };
                    this.UserMoveNext = () => {
                        this.UserCurrentPage(this.UserCurrentPage() + 1);
                        this.LoadUsers();
                    };
                    this.UserMoveLast = () => {
                        this.UserCurrentPage(this.UserTotalPages());
                        this.LoadUsers();
                    };
                    this.UserSearchKeyPressed = (event) => {
                        if (event.keyCode === 13) {
                            this.UserSearchClicked();
                        }
                    };
                    this.LoadUsers = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.GET, "/Organization/OrgUsers?id=" + this.Id() + "&search=" + encodeURIComponent(this.UserSearchText()) + "&page=" + this.UserCurrentPage(), true, {}, (data, textStatus, jqXHR) => {
                            if (!data) {
                                return;
                            }
                            this.AuthorizedUsers.removeAll();
                            if (data.AuthorizedUsers) {
                                for (let x = 0; x < data.AuthorizedUsers.length; x++) {
                                    let user = data.AuthorizedUsers[x];
                                    let userKO = new AuthorizedUserKO(user);
                                    userKO.ProgramLevel(this.ProgramLevel());
                                    userKO.USCDIProgramLevel(this.USCDIProgramLevel());
                                    userKO.CanCollapse(true);
                                    userKO.IsExpanded(false);
                                    this.AuthorizedUsers.push(ko.observable(userKO));
                                }
                            }
                            this.UserTotalCount(data.UserTotalCount);
                            this.AOUserCount(data.AOUserCount);
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "/Organization/OrgUsers");
                        }, null, null, this);
                    };
                    this.UpdateStatus = () => {
                        if (this.OrganizationStatus() == OrganizationStatus.Interested) {
                            this.OrganizationStatus(OrganizationStatus.OrganizationApproved);
                        }
                        else if (this.OrganizationStatus() == OrganizationStatus.RequestingProgramLevel) {
                            this.OrganizationStatus(OrganizationStatus.Invoicing);
                        }
                        else if (this.OrganizationStatus() == OrganizationStatus.Invoicing) {
                            this.OrganizationStatus(OrganizationStatus.ProgramLevelApproved);
                        }
                    };
                    this.canUpdate = () => {
                        if (this.OrganizationStatus() == OrganizationStatus.Interested || this.OrganizationStatus() == OrganizationStatus.Invoicing) {
                            return true;
                        }
                        else {
                            return false;
                        }
                    };
                    this.canInvoice = () => {
                        if (this.OrganizationStatus() == OrganizationStatus.RequestingProgramLevel) {
                            return true;
                        }
                        else {
                            return false;
                        }
                    };
                    this.DeclineStatus = () => {
                        if (this.OrganizationStatus() == OrganizationStatus.Interested) {
                            this.OrganizationStatus(OrganizationStatus.OrganizationDenied);
                        }
                        else if (this.OrganizationStatus() == OrganizationStatus.RequestingProgramLevel) {
                            this.OrganizationStatus(OrganizationStatus.ProgramLevelDenied);
                        }
                        else if (this.OrganizationStatus() == OrganizationStatus.Invoicing) {
                            this.OrganizationStatus(OrganizationStatus.PaymentFailed);
                        }
                    };
                    this.ResetMessage = () => {
                        this.SaveFailure(false);
                        this.SaveSuccess(false);
                    };
                    if (organization == null) {
                        return;
                    }
                    this.Id(organization.Id);
                    this.EpicCommunityMember_Id(organization.EpicCommunityMember_Id);
                    this.ProgramLevel(organization.ProgramLevel);
                    this.USCDIProgramLevel(organization.USCDIProgramLevel);
                    this.Name(organization.Name);
                    this.WebSite(organization.WebSite);
                    this.Address(organization.Address);
                    this.InternationalAddress(organization.InternationalAddress);
                    this.City(organization.City);
                    this.State(organization.State);
                    this.Zip(organization.Zip);
                    this.Country(organization.Country);
                    this.IncorporationState(organization.IncorporationState);
                    this.Products(organization.Products);
                    this.DateOfCreation(organization.DateOfCreation);
                    this.ApprovalDate(organization.ApprovalDate);
                    this.Comments(organization.Comments);
                    this.EmpUserName(organization.EmpUserName);
                    this.EmpUserPassword(organization.EmpUserPassword);
                    this.KitUserName(organization.KitUserName);
                    this.KitUserPassword(organization.KitUserPassword);
                    this.IsSherlockActivated(organization.IsSherlockActivated);
                    this.Disabled(organization.Disabled);
                    this.COIExpirationDate(organization.COIExpirationDate);
                    this.DisplayName(organization.DisplayName);
                    this.OrganizationStatus(organization.OrganizationStatus);
                    this.USCDIOrganizationStatus(organization.USCDIOrganizationStatus);
                    this.AffiliatedCustomers(organization.AffiliatedCustomers);
                    this.HasParentRegion(organization.HasParentRegion);
                    this.GovernanceMessage(organization.GovernanceMessage);
                    this.GovernanceUrl(organization.GovernanceUrl);
                    this.UserTotalCount(organization.UserTotalCount);
                    this.AOUserCount(organization.AOUserCount);
                    this.EpicVersion(organization.EpicVersion);
                    this.AllowSigningToolboxAgreement(organization.AllowSigningToolboxAgreement);
                    if (organization.AuthorizedUsers) {
                        for (let x = 0; x < organization.AuthorizedUsers.length; x++) {
                            let user = organization.AuthorizedUsers[x];
                            let userKO = new AuthorizedUserKO(user);
                            userKO.ProgramLevel(this.ProgramLevel());
                            userKO.USCDIProgramLevel(this.USCDIProgramLevel());
                            userKO.CanCollapse(true);
                            userKO.IsExpanded(false);
                            this.AuthorizedUsers.push(ko.observable(userKO));
                        }
                    }
                    if (organization.Applications) {
                        for (let x = 0; x < organization.Applications.length; x++) {
                            let app = organization.Applications[x];
                            let appKO = new ClientApplicationKO(app);
                            this.Applications.push(ko.observable(appKO));
                        }
                    }
                    if (organization.Regions) {
                        for (let x = 0; x < organization.Regions.length; x++) {
                            this.Regions.push(organization.Regions[x]);
                        }
                    }
                    this.BindableProgramLevels = super.GenerateEnumKOArray(Epic.AppOrchard.DbResources.ProgramLevel, this.ProgramLevel);
                    this.BindableStatus = super.GenerateEnumKOArray(Epic.AppOrchard.DbResources.OrganizationStatus, this.OrganizationStatus);
                    this.ProgramLevelName = ko.computed(() => {
                        return Epic.AppOrchard.Util.GetEnumValueName(this.ProgramLevel(), Epic.AppOrchard.DbResources.ProgramLevel);
                    });
                    this.USCDIProgramLevelName = ko.computed(() => {
                        return Epic.AppOrchard.Util.GetEnumValueName(this.USCDIProgramLevel(), Epic.AppOrchard.DbResources.ProgramLevel);
                    });
                    this.IsEnrolledInUSCDI = ko.computed(() => {
                        return (this.USCDIProgramLevel() == Epic.AppOrchard.DbResources.ProgramLevel.USCDIMember || this.USCDIProgramLevel() == Epic.AppOrchard.DbResources.ProgramLevel.EpicCommunityMember);
                    });
                    this.IsOnlyInUSCDI = ko.computed(() => {
                        return this.ProgramLevel() == Epic.AppOrchard.DbResources.ProgramLevel.Undefined && this.USCDIProgramLevel() == Epic.AppOrchard.DbResources.ProgramLevel.USCDIMember;
                    });
                }
            }
            DbResources.OrganizationKO = OrganizationKO;
            class AuthorizedUser extends SingleKeyedResource {
                constructor(id, organizationId, userAccountType, name, phone, email, organizationUserAssociation, canPurchase, canSubmit, canManageUsers, canActivateClients, canCreateNewAppVersions, canManageStargate, canManageConnectors, canCreateRemoteApps, disabled, deleted, userwebGUID, userwebName, sherlockEmpId, isSherlockActivated, remoteOrganizations, uscdiUserAccountType, uscdiDisabled, uscdiDeleted) {
                    super(id);
                    this.Organization_Id = 0;
                    this.UserAccountType = UserAccountType.Undefined;
                    this.Name = "";
                    this.Phone = "";
                    this.Email = "";
                    this.OrganizationUserAssociation = OrganizationUserAssociation.Undefined;
                    this.CanPurchase = false;
                    this.CanSubmit = false;
                    this.CanManageUsers = false;
                    this.CanActivateClients = false;
                    this.CanCreateNewAppVersions = false;
                    this.CanManageStargate = false;
                    this.CanManageConnectors = false;
                    this.CanCreateRemoteApps = false;
                    this.Disabled = false;
                    this.Deleted = false;
                    this.UserWebGUID = "";
                    this.UserWebName = "";
                    this.SherlockEmpId = "";
                    this.IsSherlockActivated = false;
                    this.RemoteOrganizations = [];
                    this.USCDIUserAccountType = UserAccountType.Undefined;
                    this.USCDIDisabled = false;
                    this.USCDIDeleted = false;
                    if (organizationId)
                        this.Organization_Id = organizationId;
                    if (userAccountType)
                        this.UserAccountType = userAccountType;
                    if (name)
                        this.Name = name;
                    if (phone)
                        this.Phone = phone;
                    if (email)
                        this.Email = email;
                    if (organizationUserAssociation)
                        this.OrganizationUserAssociation = organizationUserAssociation;
                    if (canPurchase)
                        this.CanPurchase = canPurchase;
                    if (canSubmit)
                        this.CanSubmit = canSubmit;
                    if (canManageUsers)
                        this.CanManageUsers = canManageUsers;
                    if (canActivateClients)
                        this.CanActivateClients = canActivateClients;
                    if (canCreateNewAppVersions)
                        this.CanCreateNewAppVersions = canCreateNewAppVersions;
                    if (canManageStargate)
                        this.CanManageStargate = canManageStargate;
                    if (canManageConnectors)
                        this.CanManageConnectors = canManageConnectors;
                    if (canCreateRemoteApps)
                        this.CanCreateRemoteApps = canCreateRemoteApps;
                    if (disabled)
                        this.Disabled = disabled;
                    if (deleted)
                        this.Deleted = deleted;
                    if (userwebGUID)
                        this.UserWebGUID = userwebGUID;
                    if (userwebName)
                        this.UserWebName = userwebName;
                    if (sherlockEmpId)
                        this.SherlockEmpId = sherlockEmpId;
                    if (isSherlockActivated)
                        this.IsSherlockActivated = isSherlockActivated;
                    if (remoteOrganizations)
                        this.RemoteOrganizations = remoteOrganizations;
                    if (uscdiUserAccountType)
                        this.USCDIUserAccountType = uscdiUserAccountType;
                    if (uscdiDisabled)
                        this.USCDIDisabled = uscdiDisabled;
                    if (uscdiDeleted)
                        this.USCDIDeleted = uscdiDeleted;
                }
            }
            DbResources.AuthorizedUser = AuthorizedUser;
            class AuthorizedUserKO extends SingleKeyedObservableResource {
                constructor(authorizedUser) {
                    super(authorizedUser);
                    this.Organization_Id = super.CreateAndRegisterValidatedKOProperty(0);
                    this.UserAccountType = super.CreateAndRegisterValidatedKOProperty(UserAccountType.Undefined);
                    this.Name = super.CreateAndRegisterValidatedKOProperty("");
                    this.Phone = super.CreateAndRegisterValidatedKOProperty("");
                    this.Email = super.CreateAndRegisterValidatedKOProperty("");
                    this.OrganizationUserAssociation = super.CreateAndRegisterValidatedKOProperty(OrganizationUserAssociation.Undefined);
                    this.CanPurchase = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanSubmit = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanManageUsers = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanActivateClients = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanCreateNewAppVersions = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanManageStargate = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanManageConnectors = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanCreateRemoteApps = super.CreateAndRegisterValidatedKOProperty(false);
                    this.Disabled = super.CreateAndRegisterValidatedKOProperty(false);
                    this.Deleted = super.CreateAndRegisterValidatedKOProperty(false);
                    this.UserWebGUID = super.CreateAndRegisterValidatedKOProperty("");
                    this.UserWebName = super.CreateAndRegisterValidatedKOProperty("");
                    this.SherlockEmpId = super.CreateAndRegisterValidatedKOProperty("");
                    this.IsSherlockActivated = super.CreateAndRegisterValidatedKOProperty(false);
                    this.NewUser = super.CreateAndRegisterValidatedKOProperty(false);
                    this.BindableOrganizationUserAssociation = null;
                    this.RemoteOrganizations = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.DirectEmployeeOrg = super.CreateAndRegisterValidatedKOProperty(0);
                    this.USCDIUserAccountType = super.CreateAndRegisterValidatedKOProperty(UserAccountType.Undefined);
                    this.USCDIDisabled = super.CreateAndRegisterValidatedKOProperty(false);
                    this.USCDIDeleted = super.CreateAndRegisterValidatedKOProperty(false);
                    this.ProgramLevel = super.CreateAndRegisterValidatedKOProperty(ProgramLevel.Undefined);
                    this.USCDIProgramLevel = super.CreateAndRegisterValidatedKOProperty(ProgramLevel.Undefined);
                    this.BindableUserAccountType = ko.computed(() => {
                        var progLevel = this.ProgramLevel();
                        let accountTypes = super.GenerateEnumKOArray(Epic.AppOrchard.DbResources.UserAccountType, this.UserAccountType);
                        if (progLevel == ProgramLevel.Epic) {
                            accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.Queued || element().value == Epic.AppOrchard.DbResources.UserAccountType.PendingApproval || element().value == Epic.AppOrchard.DbResources.UserAccountType.VendorDeveloper || element().value == Epic.AppOrchard.DbResources.UserAccountType.VendorAdmin); });
                            if (!Epic.AppOrchard.Util.IsSuperAdmin()) {
                                accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.SuperAdministrator); });
                            }
                        }
                        else {
                            accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.EpicUser || element().value == Epic.AppOrchard.DbResources.UserAccountType.EpicAdmin || element().value == Epic.AppOrchard.DbResources.UserAccountType.SuperAdministrator); });
                            if (progLevel == ProgramLevel.EpicCommunityMember) {
                                accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.VendorAdmin || element().value == Epic.AppOrchard.DbResources.UserAccountType.Queued || element().value == Epic.AppOrchard.DbResources.UserAccountType.PendingApproval); });
                            }
                        }
                        return accountTypes;
                    }, this);
                    this.BindableUSCDIUserAccountType = ko.computed(() => {
                        var progLevel = this.USCDIProgramLevel();
                        let accountTypes = super.GenerateEnumKOArray(Epic.AppOrchard.DbResources.UserAccountType, this.USCDIUserAccountType);
                        if (progLevel == ProgramLevel.Epic) {
                            accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.Queued || element().value == Epic.AppOrchard.DbResources.UserAccountType.PendingApproval || element().value == Epic.AppOrchard.DbResources.UserAccountType.VendorDeveloper || element().value == Epic.AppOrchard.DbResources.UserAccountType.VendorAdmin); });
                            if (!Epic.AppOrchard.Util.IsSuperAdmin()) {
                                accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.SuperAdministrator); });
                            }
                        }
                        else {
                            accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.EpicUser || element().value == Epic.AppOrchard.DbResources.UserAccountType.EpicAdmin || element().value == Epic.AppOrchard.DbResources.UserAccountType.SuperAdministrator); });
                            if (progLevel == ProgramLevel.EpicCommunityMember) {
                                accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.VendorAdmin || element().value == Epic.AppOrchard.DbResources.UserAccountType.Queued || element().value == Epic.AppOrchard.DbResources.UserAccountType.PendingApproval); });
                                if (progLevel = null) {
                                    accountTypes.remove(function (element) { return (element().value == Epic.AppOrchard.DbResources.UserAccountType.VendorDeveloper); });
                                }
                            }
                        }
                        return accountTypes;
                    }, this);
                    this.userAssociationChanged = (enumKO) => {
                        if (enumKO) {
                            var association = enumKO.value;
                            if (association == OrganizationUserAssociation.DirectEmployee || association == OrganizationUserAssociation.RemoteAccess) {
                                alert("Direct Employee or Remote Access association should be set from original organization. Also, please refresh your page to make sure the user shows under correct organization.");
                                return false;
                            }
                            else if (this.OrganizationUserAssociation() == OrganizationUserAssociation.DirectEmployee && association == OrganizationUserAssociation.Undefined) {
                                alert("You are about to remove this user " + this.Name() + " as a direct employee from Org " + this.Organization_Id() + ". Once you save the user will no longer be associated with this organization. Once the user logs in they will move to the original organization. The user's security points can be managed from within their initial organization.");
                            }
                            this.OrganizationUserAssociation(association);
                        }
                        return false;
                    };
                    this.directEmployeeClicked = (namedObj, event) => {
                        if (namedObj) {
                            if (event.target.checked) {
                                this.DirectEmployeeOrg(namedObj.Id);
                                $('#directEmployeeModal' + this.Id()).modal('show');
                            }
                            else {
                                this.DirectEmployeeOrg(0);
                            }
                        }
                        return true;
                    };
                    this.remoteAccessClicked = (namedObj, event) => {
                        if (namedObj) {
                            if (event.target.checked) {
                                this.RemoteOrganizations.push(namedObj.Id);
                                $('#remoteAccessModal' + this.Id()).modal('show');
                            }
                            else {
                                this.RemoteOrganizations.remove(namedObj.Id);
                            }
                        }
                        return true;
                    };
                    this.resendActivationClicked = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "AuthorizedUser/ResendActivation", false, this.ConvertToJS(), (data, textStatus, jqXHR) => {
                            var title = data.Success ? "Success" : "Failure";
                            Epic.AppOrchard.Util.Alert(title, data.Message);
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "AuthorizedUser/ResendActivation");
                        }, 3000, true, this);
                    };
                    this.DeleteUser = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "AuthorizedUser/DeleteUser", false, this.ConvertToJS(), (data, textStatus, jqXHR) => {
                            this.IsExpanded(false);
                            this.IsReadOnly(true);
                            Epic.AppOrchard.Util.Alert("Success", "User deleted successfully");
                            setTimeout(() => { this.Deleted(true); this.OnSaved(); }, 200);
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "AuthorizedUser/DeleteUser");
                        }, 3000, true, this);
                    };
                    this.UnDeleteUser = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "AuthorizedUser/UnDeleteUser", false, this.ConvertToJS(), (data, textStatus, jqXHR) => {
                            if (data.success) {
                                Epic.AppOrchard.Util.Alert("Success", "User undeleted successfully");
                                setTimeout(() => { this.Deleted(false); this.OnSaved(); }, 200);
                            }
                            else {
                                this.OnRevert();
                                Epic.AppOrchard.Util.Alert("Error", "Failed to Un-delete the user. " + data.errorMessage);
                            }
                            this.IsExpanded(false);
                            this.IsReadOnly(true);
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "AuthorizedUser/UnDeleteUser");
                        }, 3000, true, this);
                    };
                    this.ExecuteAjaxToSaveResource = () => {
                        if (!(this.NewUser())) {
                            Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "AuthorizedUser/SaveSingle", false, { data: this.ConvertToJS(), remoteOrgs: this.RemoteOrganizations() }, (data, textStatus, jqXHR) => {
                                Epic.AppOrchard.Util.Alert("Success", "User saved successfully. " + data.Error);
                                this.OnSaved();
                                this.IsExpanded(false);
                                this.IsReadOnly(true);
                            }, (jqXHR, textStatus, errorThrown) => {
                                Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "AuthorizedUser/SaveSingle");
                            }, 3000, true, this);
                        }
                        else {
                            Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "AuthorizedUser/AddSingle", false, this.ConvertToJS(), (data, textStatus, jqXHR) => {
                                Epic.AppOrchard.Util.Alert("Success", "User added successfully");
                                this.Id(data.Id);
                                this.NewUser(false);
                                this.OnSaved();
                                this.IsExpanded(false);
                                this.IsReadOnly(true);
                            }, (jqXHR, textStatus, errorThrown) => {
                                Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "AuthorizedUser/AddSingle");
                            }, 3000, true, this);
                        }
                    };
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Organization_Id: this.Organization_Id(),
                            OrganizationId: this.Organization_Id(),
                            UserAccountType: this.UserAccountType(),
                            Name: this.Name(),
                            Phone: this.Phone(),
                            Email: this.Email(),
                            OrganizationAssociation: this.OrganizationUserAssociation(),
                            CanPurchase: this.CanPurchase(),
                            CanSubmit: this.CanSubmit(),
                            CanManageUsers: this.CanManageUsers(),
                            CanActivateClients: this.CanActivateClients(),
                            CanCreateNewAppVersions: this.CanCreateNewAppVersions(),
                            CanManageStargate: this.CanManageStargate(),
                            CanManageConnectors: this.CanManageConnectors(),
                            CanCreateRemoteApps: this.CanCreateRemoteApps(),
                            Disabled: this.Disabled(),
                            Deleted: this.Deleted(),
                            UserWebGUID: this.UserWebGUID(),
                            UserWebName: this.UserWebName(),
                            SherlockEmpId: this.SherlockEmpId(),
                            IsSherlockActivated: this.IsSherlockActivated(),
                            USCDIUserAccountType: this.USCDIUserAccountType(),
                            USCDIDisabled: this.USCDIDisabled(),
                            USCDIDeleted: this.USCDIDeleted()
                        };
                    };
                    this.ConvertToJSList = () => {
                        return {
                            Id: this.Id(),
                            Organization_Id: this.Organization_Id(),
                            OrganizationId: this.Organization_Id(),
                            UserAccountType: this.UserAccountType(),
                            Name: this.Name(),
                            Phone: this.Phone(),
                            Email: this.Email(),
                            OrganizationAssociation: this.OrganizationUserAssociation(),
                            CanPurchase: this.CanPurchase(),
                            CanSubmit: this.CanSubmit(),
                            CanManageUsers: this.CanManageUsers(),
                            CanActivateClients: this.CanActivateClients(),
                            CanCreateNewAppVersions: this.CanCreateNewAppVersions(),
                            CanManageStargate: this.CanManageStargate(),
                            CanManageConnectors: this.CanManageConnectors(),
                            CanCreateRemoteApps: this.CanCreateRemoteApps(),
                            Disabled: this.Disabled(),
                            Deleted: this.Deleted(),
                            UserWebGUID: this.UserWebGUID(),
                            UserWebName: this.UserWebName(),
                            SherlockEmpId: this.SherlockEmpId(),
                            IsSherlockActivated: this.IsSherlockActivated(),
                            USCDIUserAccountType: this.USCDIUserAccountType(),
                            USCDIDisabled: this.USCDIDisabled(),
                            USCDIDeleted: this.USCDIDeleted()
                        };
                    };
                    this.OnValidateProperties = () => {
                        let result = new ResourcePropertyValidationResultCollection(!this.CanCollapse() || !this.IsReadOnly());
                        // add logic for verification
                        result.AddPropertyValidationResult("txtOrganizationUserEmail" + this.Id(), (Epic.AppOrchard.Util.IsNullOrEmpty(this.Email()) ||
                            (!(/^(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+\/=\?\^`\{\}\|~\w])*)([0-9a-z])@)(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,62}[a-z0-9])$/i.test(this.Email())) &&
                                !(/^(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+\/=\?\^`\{\}\|~\w])*)([0-9a-z])@(\[(\d{1,3}\.){3}\d{1,3}\]))$/i.test(this.Email())))), false, "Email is required.");
                        return result;
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Organization_Id = this.Organization_Id();
                        this.Resource.UserAccountType = this.UserAccountType();
                        this.Resource.Name = this.Name();
                        this.Resource.Phone = this.Phone();
                        this.Resource.Email = this.Email();
                        this.Resource.OrganizationUserAssociation = this.OrganizationUserAssociation();
                        this.Resource.CanPurchase = this.CanPurchase();
                        this.Resource.CanSubmit = this.CanSubmit();
                        this.Resource.CanManageUsers = this.CanManageUsers();
                        this.Resource.CanActivateClients = this.CanActivateClients();
                        this.Resource.CanCreateNewAppVersions = this.CanCreateNewAppVersions();
                        this.Resource.CanManageStargate = this.CanManageStargate();
                        this.Resource.CanManageConnectors = this.CanManageConnectors();
                        this.Resource.CanCreateRemoteApps = this.CanCreateRemoteApps();
                        this.Resource.Disabled = this.Disabled();
                        this.Resource.Deleted = this.Deleted();
                        this.Resource.UserWebGUID = this.UserWebGUID();
                        this.Resource.UserWebName = this.UserWebName();
                        this.Resource.SherlockEmpId = this.SherlockEmpId();
                        this.Resource.IsSherlockActivated = this.IsSherlockActivated();
                        this.Resource.RemoteOrganizations = this.RemoteOrganizations();
                        this.Resource.USCDIUserAccountType = this.USCDIUserAccountType();
                        this.Resource.USCDIDisabled = this.USCDIDisabled();
                        this.Resource.USCDIDeleted = this.USCDIDeleted();
                        this.NewUser(false);
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Organization_Id(this.Resource.Organization_Id);
                        this.UserAccountType(this.Resource.UserAccountType);
                        this.Name(this.Resource.Name);
                        this.Phone(this.Resource.Phone);
                        this.Email(this.Resource.Email);
                        this.OrganizationUserAssociation(this.Resource.OrganizationUserAssociation);
                        this.CanPurchase(this.Resource.CanPurchase);
                        this.CanSubmit(this.Resource.CanSubmit);
                        this.CanManageUsers(this.Resource.CanManageUsers);
                        this.CanActivateClients(this.Resource.CanActivateClients);
                        this.CanCreateNewAppVersions(this.Resource.CanCreateNewAppVersions);
                        this.CanManageStargate(this.Resource.CanManageStargate);
                        this.CanManageConnectors(this.Resource.CanManageConnectors);
                        this.CanCreateRemoteApps(this.Resource.CanCreateRemoteApps);
                        this.Disabled(this.Resource.Disabled);
                        this.Deleted(this.Resource.Deleted);
                        this.UserWebGUID(this.Resource.UserWebGUID);
                        this.UserWebName(this.Resource.UserWebName);
                        this.SherlockEmpId(this.Resource.SherlockEmpId);
                        this.IsSherlockActivated(this.Resource.IsSherlockActivated);
                        this.USCDIUserAccountType(this.Resource.USCDIUserAccountType);
                        this.USCDIDisabled(this.Resource.USCDIDisabled);
                        this.USCDIDeleted(this.Resource.USCDIDeleted);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Organization_Id() != this.Resource.Organization_Id) ||
                            (this.UserAccountType() != this.Resource.UserAccountType) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.Phone() != this.Resource.Phone) ||
                            (this.Email() != this.Resource.Email) ||
                            (this.OrganizationUserAssociation() != this.Resource.OrganizationUserAssociation) ||
                            (this.CanPurchase() != this.Resource.CanPurchase) ||
                            (this.CanSubmit() != this.Resource.CanSubmit) ||
                            (this.CanManageUsers() != this.Resource.CanManageUsers) ||
                            (this.CanActivateClients() != this.Resource.CanActivateClients) ||
                            (this.CanCreateNewAppVersions() != this.Resource.CanCreateNewAppVersions) ||
                            (this.CanManageStargate() != this.Resource.CanManageStargate) ||
                            (this.CanManageConnectors() != this.Resource.CanManageConnectors) ||
                            (this.CanCreateRemoteApps() != this.Resource.CanCreateRemoteApps) ||
                            (this.Disabled() != this.Resource.Disabled) ||
                            (this.IsSherlockActivated() != this.Resource.IsSherlockActivated) ||
                            (this.Deleted() != this.Resource.Deleted) ||
                            (this.USCDIUserAccountType() != this.Resource.USCDIUserAccountType) ||
                            (this.USCDIDisabled() != this.Resource.USCDIDisabled) ||
                            (this.USCDIDeleted() != this.Resource.USCDIDeleted)) {
                            return true;
                        }
                        return false;
                    }, this);
                    if (authorizedUser == null) {
                        return;
                    }
                    this.Id(authorizedUser.Id);
                    this.Organization_Id(authorizedUser.Organization_Id);
                    this.UserAccountType(authorizedUser.UserAccountType);
                    this.Name(authorizedUser.Name);
                    this.Phone(authorizedUser.Phone);
                    this.Email(authorizedUser.Email);
                    this.OrganizationUserAssociation(authorizedUser.OrganizationUserAssociation);
                    this.CanPurchase(authorizedUser.CanPurchase);
                    this.CanSubmit(authorizedUser.CanSubmit);
                    this.CanManageUsers(authorizedUser.CanManageUsers);
                    this.CanActivateClients(authorizedUser.CanActivateClients);
                    this.CanCreateNewAppVersions(authorizedUser.CanCreateNewAppVersions);
                    this.CanManageStargate(authorizedUser.CanManageStargate);
                    this.CanManageConnectors(authorizedUser.CanManageConnectors);
                    this.CanCreateRemoteApps(authorizedUser.CanCreateRemoteApps);
                    this.Disabled(authorizedUser.Disabled);
                    this.Deleted(authorizedUser.Deleted);
                    this.UserWebGUID(authorizedUser.UserWebGUID);
                    this.UserWebName(authorizedUser.UserWebName);
                    this.SherlockEmpId(authorizedUser.SherlockEmpId);
                    this.IsSherlockActivated(authorizedUser.IsSherlockActivated);
                    this.USCDIUserAccountType(authorizedUser.USCDIUserAccountType);
                    this.USCDIDisabled(authorizedUser.USCDIDisabled);
                    this.USCDIDeleted(authorizedUser.USCDIDeleted);
                    this.BindableOrganizationUserAssociation = super.GenerateEnumKOArray(Epic.AppOrchard.DbResources.OrganizationUserAssociation, this.OrganizationUserAssociation);
                    if (authorizedUser.RemoteOrganizations) {
                        for (let x = 0; x < authorizedUser.RemoteOrganizations.length; x++) {
                            this.RemoteOrganizations.push(authorizedUser.RemoteOrganizations[x]);
                        }
                    }
                }
            }
            DbResources.AuthorizedUserKO = AuthorizedUserKO;
            class ClientApplication extends SingleKeyedResource {
                constructor(id, organizationId, name, description, summary, thumbnailCount, status, version, consumerType, priceInfo, priceMode, softwareRequirements, addedOn, refreshTokensRequired, agreedToTerms, categories, organization, epicVersions, caboodleVersions, screenshots, installCount, vendorApproved, vendorApprovedEver, agreementId, website, interestedCount, tcDocuments, installStatus, userHasReviewed, userReviewDate, contentSchema, implementationGuideUrl, supportsCompare, isEpicModule, installedAnywhere, appDisclaimer, stageDisclaimer, primaryCategoryName) {
                    super(id);
                    this.Id = 0;
                    this.OrganizationId = 0;
                    this.Name = "";
                    this.Summary = "";
                    this.Description = "";
                    this.ThumbnailCount = 0;
                    this.Status = ClientApplicationStatus.Draft;
                    this.Version = "";
                    this.ConsumerType = ClientApplicationConsumerType.Undefined;
                    this.PriceInfo = "";
                    this.PriceMode = PriceMode.Undefined;
                    this.SoftwareRequirements = "";
                    this.Categories = null;
                    this.PrimaryCategoryName = "";
                    this.FeatureSets = null;
                    this.VisibleFeatureSets = "";
                    this.Organization = null;
                    this.EpicVersions = null;
                    this.VisibleEpicVersions = "";
                    this.CaboodleVersions = null;
                    this.VisibleCaboodleVersions = "";
                    this.OutgoingFunctionalities = null;
                    this.KitApiGroups = null;
                    this.IncomingApis = null;
                    this.Screenshots = null;
                    this.SubspaceEvents = null;
                    this.AddedOn = null;
                    this.RefreshTokensRequired = false;
                    this.AgreedToTerms = false;
                    this.InstallCount = 0;
                    this.VendorApproved = 0;
                    this.VendorApprovedEver = false;
                    this.AgreementId = 0;
                    this.Website = "";
                    this.InterestedCount = 0;
                    this.TCDocuments = "";
                    this.InstallStatus = 0;
                    this.UserHasReviewed = false;
                    this.UserReviewDate = "";
                    this.ContentSchema = null;
                    this.ImplementationGuideUrl = "";
                    this.SupportsCompare = false;
                    this.IsEpicModule = false;
                    this.InstalledAnywhere = false;
                    this.HideEndorsementWarning = false;
                    this.AppDisclaimer = "";
                    this.StageDisclaimer = "";
                    if (organizationId)
                        this.OrganizationId = organizationId;
                    if (name)
                        this.Name = name;
                    if (description)
                        this.Description = description;
                    if (summary)
                        this.Summary = summary;
                    if (thumbnailCount)
                        this.ThumbnailCount = thumbnailCount;
                    if (status)
                        this.Status = status;
                    if (version)
                        this.Version = version;
                    if (consumerType)
                        this.ConsumerType = consumerType;
                    if (priceInfo)
                        this.PriceInfo = priceInfo;
                    if (priceMode)
                        this.PriceMode = priceMode;
                    if (softwareRequirements)
                        this.SoftwareRequirements = softwareRequirements;
                    if (addedOn)
                        this.AddedOn = addedOn;
                    if (refreshTokensRequired)
                        this.RefreshTokensRequired = refreshTokensRequired;
                    if (agreedToTerms)
                        this.AgreedToTerms = agreedToTerms;
                    if (categories)
                        this.Categories = categories;
                    if (organization)
                        this.Organization = organization;
                    if (epicVersions)
                        this.EpicVersions = epicVersions;
                    if (caboodleVersions)
                        this.CaboodleVersions = caboodleVersions;
                    if (screenshots)
                        this.Screenshots = screenshots;
                    if (installCount)
                        this.InstallCount = installCount;
                    if (vendorApproved)
                        this.VendorApproved = vendorApproved;
                    if (vendorApprovedEver)
                        this.VendorApprovedEver = vendorApprovedEver;
                    if (agreementId)
                        this.AgreementId = agreementId;
                    if (website)
                        this.Website = website;
                    if (interestedCount)
                        this.InterestedCount = interestedCount;
                    if (tcDocuments)
                        this.TCDocuments = tcDocuments;
                    if (installStatus)
                        this.InstallStatus = installStatus;
                    if (userHasReviewed)
                        this.UserHasReviewed = userHasReviewed;
                    if (userReviewDate)
                        this.UserReviewDate = userReviewDate;
                    if (contentSchema)
                        this.ContentSchema = contentSchema;
                    if (implementationGuideUrl)
                        this.ImplementationGuideUrl = implementationGuideUrl;
                    if (supportsCompare)
                        this.SupportsCompare = supportsCompare;
                    if (isEpicModule)
                        this.IsEpicModule = isEpicModule;
                    if (installedAnywhere)
                        this.InstalledAnywhere = installedAnywhere;
                    if (appDisclaimer)
                        this.AppDisclaimer = appDisclaimer;
                    if (stageDisclaimer)
                        this.StageDisclaimer = stageDisclaimer;
                    if (primaryCategoryName)
                        this.PrimaryCategoryName = primaryCategoryName;
                }
            }
            DbResources.ClientApplication = ClientApplication;
            class ClientApplicationKO extends SingleKeyedObservableResource {
                constructor(clientApp) {
                    super(clientApp);
                    this.Id = ko.observable(0);
                    this.OrganizationId = ko.observable(0);
                    this.Name = ko.observable("");
                    this.Summary = ko.observable("");
                    this.Description = ko.observable("");
                    this.Status = ko.observable(ClientApplicationStatus.Draft);
                    this.Version = ko.observable("");
                    this.ConsumerType = ko.observable(ClientApplicationConsumerType.Undefined);
                    this.PriceInfo = ko.observable("");
                    this.PriceMode = ko.observable(PriceMode.Undefined);
                    this.SoftwareRequirements = ko.observable("");
                    this.Categories = ko.observableArray([]);
                    this.VisibleCategories = ko.observableArray([]);
                    this.FeatureSets = ko.observableArray([]);
                    this.VisibleFeatureSets = ko.observable("");
                    this.Organization = ko.observable(null);
                    this.EpicVersions = ko.observableArray([]);
                    this.CaboodleVersions = ko.observableArray([]);
                    this.VisibleCaboodleVersions = ko.observable("");
                    this.VisibleEpicVersions = ko.observable("");
                    this.OutgoingFunctionalities = ko.observableArray([]);
                    this.KitApiGroups = ko.observableArray([]);
                    this.IncomingApis = ko.observableArray([]);
                    this.Screenshots = ko.observableArray([]);
                    this.SubspaceEvents = ko.observableArray([]);
                    this.ThumbnailCount = ko.observable(0);
                    this.ThumbnailSrc = ko.observable("");
                    this.AddedOn = ko.observable(null);
                    this.RefreshTokensRequired = ko.observable(false);
                    this.AgreedToTerms = ko.observable(false);
                    this.ManualStatusEdit = ko.observable(false);
                    this.BindableStatus = null;
                    this.IsDownloaded = ko.observable(false);
                    this.DownloadedOn = ko.observable("");
                    this.DownloadedBy = ko.observable("");
                    this.VendorApproved = ko.observable(0);
                    this.VendorApprovedEver = ko.observable(false);
                    this.ParticipantTerms = ko.observable("");
                    this.InstallCount = ko.observable(0);
                    this.AgreementId = ko.observable(0);
                    this.AdminEmail = ko.observable("");
                    this.Website = ko.observable("");
                    this.IsInterested = ko.observable(false);
                    this.InterestedOn = ko.observable("");
                    this.InterestedCount = ko.observable(0);
                    this.TCDocuments = ko.observable("");
                    this.TCPackages = ko.observableArray([]);
                    this.TCPackagesLoading = ko.observable(false);
                    this.InstallStatus = ko.observable(0);
                    this.EditableInstallStatus = ko.observable(0);
                    this.UserHasReviewed = ko.observable(false);
                    this.UserReviewDate = ko.observable("");
                    this.UnauthorizedUser = ko.observable(false);
                    this.ContentSchema = ko.observable(null);
                    this.ImplementationGuideUrl = ko.observable("");
                    this.APILicenseTermsId = ko.observable(-1);
                    this.PreviousAPILicenseExists = ko.observable(false);
                    this.SelectedAppOtherVersions = ko.observableArray([]);
                    this.NewestVersion = ko.observable(-1);
                    this.ProdVersion = ko.observable(null);
                    this.NonProdVersion = ko.observable(null);
                    this.RequestedVersion = ko.observable(null);
                    this.SupportsCompare = ko.observable(false);
                    this.SupportsLicensing = ko.observable(false);
                    this.IsEpicModule = ko.observable(false);
                    this.InstalledAnywhere = ko.observable(false);
                    this.NotImplementingNowDetails = ko.observable(null);
                    this.TempNotImplementingNowDetails = ko.observable(new DbResources.NotImplementingNowModelKO());
                    this.NotImplementingNow = ko.computed(() => {
                        return this.NotImplementingNowDetails() !== null;
                    }, this);
                    this.RequiresFutureEpicVersion = ko.observable(false);
                    this.HideEndorsementWarning = ko.observable(false);
                    this.AppDisclaimer = ko.observable("");
                    this.StageDisclaimer = ko.observable("");
                    this.PrimaryCategoryName = ko.observable("");
                    this.AddCategory = (category) => {
                        this.VisibleCategories.push(category.Name);
                        if (category.Children && category.Children.length > 0) {
                            for (let index = 0; index < category.Children.length; index++) {
                                let child = category.Children[index];
                                if (child && child.Name) {
                                    this.AddCategory(child);
                                }
                            }
                        }
                    };
                    this.ShortSummary = ko.computed(() => {
                        const maxLength = 130;
                        if (!this.Summary || !this.Summary())
                            return "";
                        if (this.Summary().length > maxLength) {
                            return this.Summary().substring(0, maxLength).trim() + "...";
                        }
                        else {
                            return this.Summary();
                        }
                    });
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Name: this.Name(),
                            Version: this.Version(),
                            ConsumerType: this.ConsumerType(),
                            Status: this.Status()
                        };
                    };
                    this.OnValidateProperties = () => {
                        let result = new ResourcePropertyValidationResultCollection(!this.CanCollapse() || !this.IsReadOnly());
                        // add logic for verification
                        if (!this.Name() || this.Name().length == 0) {
                            result.AddPropertyValidationResult("txtApplicationName" + this.Id(), true, false, "Name is required.");
                        }
                        return result;
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.OrganizationId = this.OrganizationId();
                        this.Resource.Name = this.Name();
                        this.Resource.Description = this.Description();
                        this.Resource.Version = this.Version();
                        this.Resource.Status = this.Status();
                        this.Resource.ConsumerType = this.ConsumerType();
                        this.Resource.PriceInfo = this.PriceInfo();
                        this.Resource.PriceMode = this.PriceMode();
                        this.Resource.SoftwareRequirements = this.SoftwareRequirements();
                        this.Resource.AddedOn = this.AddedOn();
                        this.Resource.RefreshTokensRequired = this.RefreshTokensRequired();
                        this.Resource.AgreedToTerms = this.AgreedToTerms();
                        this.Resource.VendorApproved = this.VendorApproved();
                        this.Resource.VendorApprovedEver = this.VendorApprovedEver();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.OrganizationId(this.Resource.OrganizationId);
                        this.Name(this.Resource.Name);
                        this.Description(this.Resource.Description);
                        this.Status(this.Resource.Status);
                        this.Version(this.Resource.Version);
                        this.ConsumerType(this.Resource.ConsumerType);
                        this.PriceInfo(this.Resource.PriceInfo);
                        this.PriceMode(this.Resource.PriceMode);
                        this.SoftwareRequirements(this.Resource.SoftwareRequirements);
                        this.AddedOn(this.Resource.AddedOn);
                        this.RefreshTokensRequired(this.Resource.RefreshTokensRequired);
                        this.AgreedToTerms(this.Resource.AgreedToTerms);
                        this.VendorApproved(this.Resource.VendorApproved);
                        this.VendorApprovedEver(this.Resource.VendorApprovedEver);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.OrganizationId() != this.Resource.OrganizationId) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.Description() != this.Resource.Description) ||
                            (this.Status() != this.Resource.Status) ||
                            (this.Version() != this.Resource.Version) ||
                            (this.ConsumerType() != this.Resource.ConsumerType) ||
                            (this.PriceInfo() != this.Resource.PriceInfo) ||
                            (this.PriceMode() != this.Resource.PriceMode) ||
                            (this.SoftwareRequirements() != this.Resource.SoftwareRequirements) ||
                            (this.AddedOn() != this.Resource.AddedOn) ||
                            (this.RefreshTokensRequired() != this.Resource.RefreshTokensRequired) ||
                            (this.AgreedToTerms() != this.Resource.AgreedToTerms) ||
                            (this.VendorApproved() != this.Resource.VendorApproved) ||
                            (this.VendorApprovedEver() != this.Resource.VendorApprovedEver)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.HasThumbnail = ko.computed(() => {
                        return this.ThumbnailCount() > 0 || !Epic.AppOrchard.Util.IsNullOrEmpty(this.ThumbnailSrc());
                    }, this);
                    this.IsAutoDownloaded = ko.computed(() => {
                        return !Epic.AppOrchard.Util.IsNullOrEmpty(this.DownloadedBy()) && this.DownloadedBy() == "__auto__";
                    });
                    this.AppClassificationClass = ko.computed(() => {
                        if (this.InstalledAnywhere()) {
                            return "installed";
                        }
                        return "not-installed";
                    });
                    if (clientApp == null) {
                        return;
                    }
                    this.Id(clientApp.Id);
                    this.OrganizationId(clientApp.OrganizationId);
                    this.Name(clientApp.Name);
                    this.Description(clientApp.Description);
                    this.Summary(clientApp.Summary);
                    this.ThumbnailCount(clientApp.ThumbnailCount);
                    this.Status(clientApp.Status);
                    this.Version(clientApp.Version);
                    this.ConsumerType(clientApp.ConsumerType);
                    this.PriceInfo(clientApp.PriceInfo);
                    this.PriceMode(clientApp.PriceMode);
                    this.SoftwareRequirements(clientApp.SoftwareRequirements);
                    this.AddedOn(clientApp.AddedOn);
                    this.RefreshTokensRequired(clientApp.RefreshTokensRequired);
                    this.AgreedToTerms(clientApp.AgreedToTerms);
                    this.InstallCount(clientApp.InstallCount);
                    this.VendorApproved(clientApp.VendorApproved);
                    this.VendorApprovedEver(clientApp.VendorApprovedEver);
                    this.AgreementId(clientApp.AgreementId);
                    this.Website(clientApp.Website);
                    this.InterestedCount(clientApp.InterestedCount);
                    this.TCDocuments(clientApp.TCDocuments);
                    this.InstallStatus(clientApp.InstallStatus);
                    this.UserHasReviewed(clientApp.UserHasReviewed);
                    this.UserReviewDate(clientApp.UserReviewDate);
                    this.ContentSchema(clientApp.ContentSchema);
                    this.ImplementationGuideUrl(clientApp.ImplementationGuideUrl);
                    this.SupportsCompare(clientApp.SupportsCompare);
                    this.IsEpicModule(clientApp.IsEpicModule);
                    this.InstalledAnywhere(clientApp.InstalledAnywhere);
                    this.HideEndorsementWarning(clientApp.HideEndorsementWarning);
                    this.AppDisclaimer(clientApp.AppDisclaimer);
                    this.StageDisclaimer(clientApp.StageDisclaimer);
                    this.PrimaryCategoryName(clientApp.PrimaryCategoryName);
                    if (clientApp.Organization) {
                        this.Organization(new OrganizationKO(clientApp.Organization));
                    }
                    if (clientApp.Categories) {
                        for (let index = 0; index < clientApp.Categories.length; index++) {
                            let category = clientApp.Categories[index];
                            this.Categories.push(new CategoryKO(new Category(category.Id, category.Name, category.IconId)));
                            if (category && category.Name) {
                                this.AddCategory(category);
                            }
                        }
                    }
                    if (clientApp.FeatureSets) {
                        for (let index = 0; index < clientApp.FeatureSets.length; index++) {
                            var featSet = clientApp.FeatureSets[index];
                            this.FeatureSets.push(new FeatureSetKO(new FeatureSet(featSet.Id, featSet.Name, featSet.Description)));
                        }
                    }
                    else if (clientApp.VisibleFeatureSets) {
                        this.VisibleFeatureSets(clientApp.VisibleFeatureSets);
                    }
                    if (clientApp.EpicVersions) {
                        for (let index = 0; index < clientApp.EpicVersions.length; index++) {
                            var epicVers = clientApp.EpicVersions[index];
                            this.EpicVersions.push(new EpicVersionKO(new EpicVersion(epicVers.Id, epicVers.Name)));
                        }
                    }
                    else if (clientApp.VisibleEpicVersions) {
                        this.VisibleEpicVersions(clientApp.VisibleEpicVersions);
                    }
                    if (clientApp.CaboodleVersions) {
                        for (let index = 0; index < clientApp.CaboodleVersions.length; index++) {
                            var caboodleVers = clientApp.CaboodleVersions[index];
                            this.CaboodleVersions.push(new CaboodleVersionKO(new CaboodleVersion(caboodleVers.Id, caboodleVers.Name)));
                        }
                    }
                    else if (clientApp.VisibleCaboodleVersions) {
                        this.VisibleCaboodleVersions(clientApp.VisibleCaboodleVersions);
                    }
                    if (clientApp.Screenshots) {
                        for (let index = 0; index < clientApp.Screenshots.length; index++) {
                            var shot = clientApp.Screenshots[index];
                            this.Screenshots.push(new ScreenshotKO(new Screenshot(shot.Id, shot.ImageData)));
                        }
                    }
                    if (clientApp.OutgoingFunctionalities) {
                        for (let index = 0; index < clientApp.OutgoingFunctionalities.length; index++) {
                            this.OutgoingFunctionalities.push(clientApp.OutgoingFunctionalities[index]);
                        }
                    }
                    if (clientApp.KitApiGroups) {
                        for (let index = 0; index < clientApp.KitApiGroups.length; index++) {
                            let api = clientApp.KitApiGroups[index];
                            this.KitApiGroups.push(new GalleryApiKO(api));
                        }
                    }
                    if (clientApp.IncomingApis) {
                        for (let index = 0; index < clientApp.IncomingApis.length; index++) {
                            let api = clientApp.IncomingApis[index];
                            this.IncomingApis.push(new GalleryApiKO(api));
                        }
                    }
                    if (clientApp.SubspaceEvents) {
                        for (let index = 0; index < clientApp.SubspaceEvents.length; index++) {
                            let api = clientApp.SubspaceEvents[index];
                            this.SubspaceEvents.push(new GalleryApiKO(api));
                        }
                    }
                    this.BindableStatus = super.GenerateEnumKOArray(Epic.AppOrchard.DbResources.ClientApplicationStatus, this.Status);
                }
                ;
            }
            DbResources.ClientApplicationKO = ClientApplicationKO;
            class ClientApplication_Uri extends SingleKeyedResource {
                constructor(clientApplication_Id, uriPrefix, uri, environmentType) {
                    super(clientApplication_Id);
                    this.ClientApplication_Id = 0;
                    this.Prefix = "";
                    this.Body = "";
                    this.EnvironmentType = EnvironmentType.Nonprod;
                    if (clientApplication_Id)
                        this.ClientApplication_Id = clientApplication_Id;
                    if (uriPrefix)
                        this.Prefix = uriPrefix;
                    if (uri)
                        this.Body = uri;
                    if (environmentType)
                        this.EnvironmentType = environmentType;
                }
            }
            DbResources.ClientApplication_Uri = ClientApplication_Uri;
            class ClientApplication_UriKO extends SingleKeyedObservableResource {
                constructor(appUri, maxLength) {
                    super(appUri);
                    this.ClientApplication_Id = ko.observable(0);
                    this.Prefix = ko.observable("");
                    this.Placeholder = ko.observable("");
                    this.UriPrefixItem = ko.observable(new DbResources.UrlProtocolSelectItemKO(new DbResources.UrlProtocolSelectItem(-1, null)));
                    this.Body = ko.observable("").extend({ deferred: true });
                    this.EnvironmentType = ko.observable(DbResources.EnvironmentType.Both);
                    this.EnvironmentTypeItem = ko.observable(new DbResources.EnvironmentSelectItemKO(new DbResources.EnvironmentSelectItem(EnvironmentType.Nonprod, EnvironmentType.Nonprod)));
                    this.MaxLength = ko.observable(0);
                    this.IsDuplicate = ko.observable(false);
                    this.IsEmpty = ko.computed(() => {
                        return this.Body().length == 0;
                    }, this);
                    this.IsValidLength = ko.computed(() => {
                        return (this.Prefix() + this.Body()).length <= this.MaxLength();
                    }, this);
                    this.ShowError = ko.computed(() => {
                        return !this.IsValidLength() || this.IsEmpty() || this.IsDuplicate();
                    }, this);
                    this.InputTitle = ko.computed(() => {
                        if (!this.IsValidLength())
                            return "This uri is too long. The max length is " + this.MaxLength() + " characters";
                        else if (this.IsDuplicate())
                            return "This uri is a duplicate.";
                        else if (this.IsEmpty())
                            return "This uri is empty.";
                        else
                            return "";
                    }, this);
                    this.ConvertToJS = () => {
                        return {
                            ClientApplication_Id: this.ClientApplication_Id(),
                            Prefix: this.Prefix(),
                            Body: this.Body(),
                            EnvironmentType: this.EnvironmentType()
                        };
                    };
                    this.OnSaved = () => {
                        this.Resource.ClientApplication_Id = this.ClientApplication_Id();
                        this.Resource.Prefix = this.Prefix();
                        this.Resource.EnvironmentType = this.EnvironmentType();
                        this.Resource.Body = this.Body();
                    };
                    this.OnRevert = () => {
                        this.ClientApplication_Id(this.Resource.ClientApplication_Id);
                        this.EnvironmentType(this.Resource.EnvironmentType);
                        this.Prefix(this.Resource.Prefix);
                        this.Body(this.Resource.Body);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.ClientApplication_Id() != this.Resource.ClientApplication_Id) ||
                            (this.EnvironmentType() != this.Resource.EnvironmentType) ||
                            (this.Prefix() != this.Resource.Prefix) ||
                            (this.Body() != this.Resource.Body)) {
                            return true;
                        }
                        return false;
                    }, this);
                    if (appUri == null) {
                        return;
                    }
                    this.ClientApplication_Id(appUri.ClientApplication_Id);
                    this.Placeholder("www.myapp.com/callback");
                    appUri.Body = appUri.Body.trim();
                    if (appUri.Body.indexOf(HttpUriPrefix) === 0) {
                        this.Prefix(HttpUriPrefix);
                        this.UriPrefixItem(UrlProtocolSelectItemKO.httpItem);
                        this.Body(appUri.Body.substring(7));
                    }
                    else if (appUri.Body.indexOf(DbResources.HttpsUriPrefix) === 0) {
                        this.Prefix(DbResources.HttpsUriPrefix);
                        this.UriPrefixItem(UrlProtocolSelectItemKO.httpsItem);
                        this.Body(appUri.Body.substring(8));
                    }
                    else if (appUri.Body.indexOf("://") >= 0) {
                        this.Prefix(CustomUriPrefix);
                        this.UriPrefixItem(UrlProtocolSelectItemKO.customItem);
                        this.Placeholder("myapp://callback");
                        this.Body(appUri.Body);
                    }
                    else {
                        this.Prefix(appUri.Prefix);
                        if (appUri.Prefix == DbResources.HttpsUriPrefix) {
                            this.UriPrefixItem(UrlProtocolSelectItemKO.httpsItem);
                        }
                        else if (appUri.Prefix == HttpUriPrefix) {
                            this.UriPrefixItem(UrlProtocolSelectItemKO.httpItem);
                        }
                        else if (appUri.Prefix == CustomUriPrefix) {
                            this.UriPrefixItem(UrlProtocolSelectItemKO.customItem);
                            this.Placeholder("myapp://callback");
                        }
                        this.Body(appUri.Body);
                    }
                    this.EnvironmentType(appUri.EnvironmentType);
                    if (appUri.EnvironmentType == EnvironmentType.Both) {
                        this.EnvironmentTypeItem(EnvironmentSelectItemKO.bothEnvironmentItem);
                    }
                    else if (appUri.EnvironmentType == EnvironmentType.Nonprod) {
                        this.EnvironmentTypeItem(EnvironmentSelectItemKO.nonProdItem);
                    }
                    else if (appUri.EnvironmentType == EnvironmentType.Prod) {
                        this.EnvironmentTypeItem(EnvironmentSelectItemKO.prodItem);
                    }
                    var model = this;
                    this.UriPrefixItem.subscribe(function (newVal) {
                        model.Placeholder("www.myapp.com/callback");
                        if (newVal.Protocol() == Protocol.http) {
                            model.Prefix(HttpUriPrefix);
                            model.EnvironmentType(EnvironmentType.Nonprod);
                            model.EnvironmentTypeItem(EnvironmentSelectItemKO.nonProdItem);
                        }
                        else if (newVal.Protocol() == Protocol.https) {
                            model.Prefix(DbResources.HttpsUriPrefix);
                        }
                        else if (newVal.Protocol() == Protocol.custom) {
                            model.Prefix(CustomUriPrefix);
                            model.Placeholder("myapp://callback");
                        }
                    });
                    this.EnvironmentTypeItem.subscribe(function (newVal) {
                        model.EnvironmentType(newVal.EnvironmentType());
                        if ((model.EnvironmentType() == EnvironmentType.Both || model.EnvironmentType() == EnvironmentType.Prod)
                            && model.UriPrefixItem() !== UrlProtocolSelectItemKO.customItem) {
                            model.UriPrefixItem(UrlProtocolSelectItemKO.httpsItem);
                            model.Prefix(DbResources.HttpsUriPrefix);
                        }
                    });
                    this.Body.subscribe(function (newVal) {
                        newVal = newVal.trim();
                        model.Placeholder("www.myapp.com/callback");
                        if (newVal.indexOf(HttpUriPrefix) === 0) {
                            model.Prefix(HttpUriPrefix);
                            model.UriPrefixItem(UrlProtocolSelectItemKO.httpItem);
                            model.Body(newVal.substring(7));
                        }
                        else if (newVal.indexOf(DbResources.HttpsUriPrefix) === 0) {
                            model.Prefix(DbResources.HttpsUriPrefix);
                            model.UriPrefixItem(UrlProtocolSelectItemKO.httpsItem);
                            model.Body(newVal.substring(8));
                        }
                        else if (newVal.indexOf("://") >= 0) {
                            model.Prefix(CustomUriPrefix);
                            model.UriPrefixItem(UrlProtocolSelectItemKO.customItem);
                            model.Placeholder("myapp://callback");
                            model.Body(newVal); // use trimmed val
                        }
                        else {
                            model.Body(newVal); // use trimmed val
                        }
                    });
                    // custom URLs store the word "custom" in the URL so subtract that amount from allowed length
                    this.MaxLength(maxLength - (model.UriPrefixItem() === UrlProtocolSelectItemKO.customItem ? 6 : 0));
                }
                ;
            }
            ClientApplication_UriKO.OriginMaxLength = 250;
            ClientApplication_UriKO.RedirectUriMaxLength = 400;
            ClientApplication_UriKO.JKUMaxLength = 400;
            DbResources.ClientApplication_UriKO = ClientApplication_UriKO;
            class UrlProtocolSelectItem extends DbResources.SingleKeyedResource {
                constructor(id, protocol) {
                    super(id);
                    this.Protocol = DbResources.Protocol.https;
                    if (protocol)
                        this.Protocol = protocol;
                }
            }
            DbResources.UrlProtocolSelectItem = UrlProtocolSelectItem;
            class UrlProtocolSelectItemKO extends DbResources.SingleKeyedObservableResource {
                constructor(item) {
                    super(item);
                    this.Protocol = super.CreateAndRegisterValidatedKOProperty(DbResources.Protocol.https);
                    this.ConvertToJS = () => {
                        return {
                            Protocol: this.Protocol()
                        };
                    };
                    this.ConvertToJSList = () => {
                        return {
                            Protocol: this.Protocol()
                        };
                    };
                    this.OnSaved = () => {
                        this.Resource.Protocol = this.Protocol();
                    };
                    this.OnRevert = () => {
                        this.Protocol(this.Resource.Protocol);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Protocol() != this.Resource.Protocol)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.DisplayText = ko.computed(() => {
                        if (this.Resource == null) {
                            return "";
                        }
                        if (this.Protocol() == Protocol.http) {
                            return HttpUriPrefix;
                        }
                        else if (this.Protocol() == Protocol.https) {
                            return DbResources.HttpsUriPrefix;
                        }
                        else if (this.Protocol() == Protocol.custom) {
                            return CustomUriPrefix;
                        }
                    }, this);
                    if (item == null) {
                        return;
                    }
                    this.Protocol(item.Protocol || DbResources.Protocol.https);
                }
            }
            UrlProtocolSelectItemKO.httpItem = new UrlProtocolSelectItemKO(new DbResources.UrlProtocolSelectItem(DbResources.Protocol.http, DbResources.Protocol.http));
            UrlProtocolSelectItemKO.httpsItem = new UrlProtocolSelectItemKO(new DbResources.UrlProtocolSelectItem(DbResources.Protocol.https, DbResources.Protocol.https));
            UrlProtocolSelectItemKO.customItem = new UrlProtocolSelectItemKO(new DbResources.UrlProtocolSelectItem(DbResources.Protocol.custom, DbResources.Protocol.custom));
            DbResources.UrlProtocolSelectItemKO = UrlProtocolSelectItemKO;
            class EnvironmentSelectItem extends DbResources.SingleKeyedResource {
                constructor(id, environmentType) {
                    super(id);
                    this.EnvironmentType = EnvironmentType.Both;
                    if (environmentType)
                        this.EnvironmentType = environmentType;
                }
            }
            DbResources.EnvironmentSelectItem = EnvironmentSelectItem;
            class EnvironmentSelectItemKO extends DbResources.SingleKeyedObservableResource {
                constructor(item) {
                    super(item);
                    this.EnvironmentType = super.CreateAndRegisterValidatedKOProperty(null);
                    this.ConvertToJS = () => {
                        return {
                            EnvironmentType: this.EnvironmentType()
                        };
                    };
                    this.ConvertToJSList = () => {
                        return {
                            EnvironmentType: this.EnvironmentType()
                        };
                    };
                    this.OnSaved = () => {
                        this.Resource.EnvironmentType = this.EnvironmentType();
                    };
                    this.OnRevert = () => {
                        this.EnvironmentType(this.Resource.EnvironmentType);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.EnvironmentType() != this.Resource.EnvironmentType)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.DisplayText = ko.computed(() => {
                        if (this.Resource == null) {
                            return "";
                        }
                        if (this.EnvironmentType() == EnvironmentType.Both) {
                            return "Both";
                        }
                        else if (this.EnvironmentType() == EnvironmentType.Nonprod) {
                            return "Non-production";
                        }
                        else if (this.EnvironmentType() == EnvironmentType.Prod) {
                            return "Production";
                        }
                    }, this);
                    if (item == null) {
                        return;
                    }
                    this.EnvironmentType(item.EnvironmentType || DbResources.EnvironmentType.Both);
                }
            }
            EnvironmentSelectItemKO.bothEnvironmentItem = new EnvironmentSelectItemKO(new DbResources.EnvironmentSelectItem(DbResources.EnvironmentType.Both, DbResources.EnvironmentType.Both));
            EnvironmentSelectItemKO.nonProdItem = new EnvironmentSelectItemKO(new DbResources.EnvironmentSelectItem(DbResources.EnvironmentType.Nonprod, DbResources.EnvironmentType.Nonprod));
            EnvironmentSelectItemKO.prodItem = new EnvironmentSelectItemKO(new DbResources.EnvironmentSelectItem(DbResources.EnvironmentType.Prod, DbResources.EnvironmentType.Prod));
            DbResources.EnvironmentSelectItemKO = EnvironmentSelectItemKO;
            class FhirIdGenerationSchemeOption {
                constructor(value, disabled = false) {
                    this.Value = FhirIdVersionType.VersionA;
                    this.DisplayText = "";
                    this.Helptext = "";
                    this.Disabled = false;
                    this.Value = value;
                    this.Disabled = disabled;
                    switch (value) {
                        case FhirIdVersionType.VersionA:
                            this.DisplayText = "Use Unconstrained FHIR IDs";
                            this.Helptext = "The app will receive and must send the same type of FHIR IDs that were always generated before the February 2022 Epic release. These were longer than the FHIR spec maximum length of 64 characters in some cases.";
                            break;
                        case FhirIdVersionType.VersionB:
                            this.DisplayText = "Use 64-Character-Limited FHIR IDs for USCDI v1 FHIR Resources";
                            this.Helptext = (disabled ? FhirIdGenerationSchemeOption.disabledText : "") + "The app will receive and must send FHIR IDs that have a maximum length of 64 characters for USCDI v1 resources (guaranteed), though other resources may also have a maximum length of 64 characters. This option will only have an effect for FHIR resources with a FHIR version of STU3 or greater.";
                            break;
                        case FhirIdVersionType.Any:
                            this.DisplayText = "Accept Any Type of FHIR ID (Not Recommended)";
                            this.Helptext = (disabled ? FhirIdGenerationSchemeOption.disabledText : "") + "The app will usually receive 64-character-limited FHIR IDs for USCDI v1 resources but both unconstrained FHIR IDs and 64-character-limited FHIR IDs can be accepted from the app. This option is not recommended for general use. This option will only have an effect for FHIR resources with a FHIR version of STU3 or greater.";
                            break;
                    }
                }
            }
            FhirIdGenerationSchemeOption.disabledText = "This option is not supported in the Epic version currently in use in this customer's Epic production environment. ";
            DbResources.FhirIdGenerationSchemeOption = FhirIdGenerationSchemeOption;
            class Category extends SingleKeyedResource {
                constructor(id, name, iconId, children, selected, compareEnabled) {
                    super(id);
                    this.Id = 0;
                    this.Name = "";
                    this.IconId = 0;
                    this.IsExpanded = false;
                    this.Selected = false;
                    this.CompareEnabled = false;
                    if (name)
                        this.Name = name;
                    if (iconId)
                        this.IconId = iconId;
                    if (children)
                        this.Children = children;
                    if (selected)
                        this.Selected = selected;
                    if (compareEnabled)
                        this.CompareEnabled = compareEnabled;
                    this.IsExpanded = false;
                }
            }
            DbResources.Category = Category;
            class CategoryKO extends SingleKeyedObservableResource {
                constructor(category) {
                    super(category);
                    this.Name = ko.observable("");
                    this.IconId = ko.observable(0);
                    this.Icon = ko.observable("");
                    this.Selected = ko.observable(false);
                    this.IsExpanded = ko.observable(false);
                    this.Children = ko.observableArray([]);
                    this.Parent = ko.observable(null);
                    this.CompareEnabled = ko.observable(false);
                    this.IsRoot = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        return !this.Parent();
                    }, this);
                    this.HasChildren = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if (this.Children() && this.Children().length > 0) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Name = this.Name();
                        this.Resource.Selected = this.Selected();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Name(this.Resource.Name);
                        this.Selected(this.Resource.Selected);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.Selected() != this.Resource.Selected)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.MarginLeft = ko.computed(() => {
                        if (this.Resource == null) {
                            return "";
                        }
                        return this.AncestorCount() * 15 + "px";
                    }, this);
                    if (category == null) {
                        return;
                    }
                    this.Name(category.Name);
                    this.Selected(category.Selected);
                    this.CompareEnabled(category.CompareEnabled);
                    if (category.IsExpanded) {
                        this.IsExpanded(category.IsExpanded);
                    }
                    this.IconId(category.IconId);
                    if (this.IconId() > 0 && this.IconId() < DbResources.AppCategoryIcons.length) {
                        this.Icon("glyphicon glyphicon-" + DbResources.AppCategoryIcons[this.IconId()]);
                    }
                    else {
                        this.Icon("glyphicon glyphicon-" + DbResources.AppCategoryIcons[0]);
                    }
                    if (category.Children) {
                        for (let index = 0; index < category.Children.length; index++) {
                            let child = new CategoryKO(category.Children[index]);
                            child.Parent(this);
                            this.Children.push(child);
                        }
                    }
                }
                ;
                RecursiveSelectedCategories() {
                    if (this.Resource == null) {
                        return [];
                    }
                    let selectedCategories = [];
                    if (this.Selected()) {
                        selectedCategories.push(this);
                        if (this.HasChildren()) {
                            for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                                selectedCategories = selectedCategories.concat(this.Children()[childIndex].RecursiveSelectedCategories());
                            }
                        }
                    }
                    return selectedCategories;
                }
                RecursiveSelectedCategoryIds() {
                    if (this.Resource == null) {
                        return [];
                    }
                    let selectedIds = [];
                    if (this.Selected()) {
                        selectedIds.push(this.Id());
                        if (this.HasChildren()) {
                            for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                                selectedIds = selectedIds.concat(this.Children()[childIndex].RecursiveSelectedCategoryIds());
                            }
                        }
                    }
                    return selectedIds;
                }
                /**
                 * Gets categories that are selected when all children are also selected. Otherwise,
                 * recurses into children.
                 * */
                RecursiveSelectedCategoriesForFilter() {
                    let toReturn = [];
                    if (this.Resource == null) {
                        return toReturn;
                    }
                    if (this.Selected() && this.AllChildrenSelected()) {
                        toReturn.push(this);
                    }
                    else if (this.HasChildren()) {
                        for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                            let childCategory = this.Children()[childIndex];
                            toReturn = toReturn.concat(childCategory.RecursiveSelectedCategoriesForFilter());
                        }
                    }
                    return toReturn;
                }
                AllChildrenSelected() {
                    if (!this.HasChildren())
                        return true;
                    for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                        let child = this.Children()[childIndex];
                        if (!child.Selected() || !child.AllChildrenSelected()) {
                            return false;
                        }
                    }
                    return true;
                }
                AnyChildrenSelected() {
                    if (!this.HasChildren())
                        return false;
                    for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                        let child = this.Children()[childIndex];
                        if (child.Selected() || child.AnyChildrenSelected()) {
                            return true;
                        }
                    }
                    return false;
                }
                AncestorCount() {
                    let count = 0;
                    if (this.Parent()) {
                        count = this.Parent().AncestorCount() + 1;
                    }
                    return count;
                }
                Unselect() {
                    this.Selected(false);
                    if (this.HasChildren()) {
                        for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                            this.Children()[childIndex].Unselect();
                        }
                    }
                }
                Select() {
                    this.Selected(true);
                    if (this.HasChildren()) {
                        for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                            this.Children()[childIndex].Select();
                        }
                    }
                }
                UnselectParent() {
                    if (this.Parent()) {
                        this.Parent().Selected(false);
                        this.Parent().UnselectParent();
                    }
                }
                SelectParent() {
                    if (this.Parent()) {
                        this.Parent().Selected(true);
                        this.Parent().SelectParent();
                    }
                }
                SelectIfInList(idList) {
                    if (idList.indexOf(this.Id()) >= 0) {
                        this.Select();
                    }
                    if (this.HasChildren()) {
                        for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                            this.Children()[childIndex].SelectIfInList(idList);
                        }
                    }
                }
                UnselectIfChildrenAreUnselected() {
                    if (!this.Selected() || !this.HasChildren())
                        return;
                    for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                        let childCategory = this.Children()[childIndex];
                        childCategory.UnselectIfChildrenAreUnselected();
                    }
                    if (!this.AnyChildrenSelected()) {
                        this.Selected(false);
                    }
                }
                UpdateDOM() {
                    let checkboxElement = $("#CategoryCheckbox" + this.Id());
                    if (this.Selected()) {
                        if (!this.HasChildren()) {
                            checkboxElement.prop("checked", true);
                            checkboxElement.prop("indeterminate", false);
                        }
                        else if (this.AllChildrenSelected()) {
                            checkboxElement.prop("checked", true);
                            checkboxElement.prop("indeterminate", false);
                        }
                        else {
                            checkboxElement.prop("checked", false);
                            checkboxElement.prop("indeterminate", true);
                        }
                    }
                    else if (this.AnyChildrenSelected()) {
                        checkboxElement.prop("checked", false);
                        checkboxElement.prop("indeterminate", true);
                    }
                    else {
                        checkboxElement.prop("checked", false);
                        checkboxElement.prop("indeterminate", false);
                    }
                    if (this.HasChildren()) {
                        for (let childIndex = 0; childIndex < this.Children().length; childIndex++) {
                            this.Children()[childIndex].UpdateDOM();
                        }
                    }
                }
            }
            DbResources.CategoryKO = CategoryKO;
            class EpicVersion extends SingleKeyedResource {
                constructor(id, name, obsolete) {
                    super(id);
                    this.Id = 0;
                    this.Name = "";
                    this.Obsolete = false;
                    if (name)
                        this.Name = name;
                    if (obsolete)
                        this.Obsolete = obsolete;
                }
            }
            DbResources.EpicVersion = EpicVersion;
            class EpicVersionKO extends SingleKeyedObservableResource {
                constructor(vers) {
                    super(vers);
                    this.Id = ko.observable(0);
                    this.Name = ko.observable("");
                    this.Obsolete = ko.observable(false);
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Name = this.Name();
                        this.Resource.Obsolete = this.Obsolete();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Name(this.Resource.Name);
                        this.Obsolete(this.Resource.Obsolete);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.Obsolete() != this.Resource.Obsolete)) {
                            return true;
                        }
                        return false;
                    }, this);
                    if (vers == null) {
                        return;
                    }
                    this.Id(vers.Id);
                    this.Name(vers.Name);
                    this.Obsolete(vers.Obsolete);
                }
                ;
            }
            DbResources.EpicVersionKO = EpicVersionKO;
            class CaboodleVersion extends EpicVersion {
                constructor(id, name, obsolete) {
                    super(id, name, obsolete);
                }
                ;
            }
            DbResources.CaboodleVersion = CaboodleVersion;
            class CaboodleVersionKO extends SingleKeyedObservableResource {
                constructor(vers) {
                    super(vers);
                    this.Id = ko.observable(0);
                    this.Name = ko.observable("");
                    if (vers == null) {
                        return;
                    }
                    this.Id(vers.Id);
                    this.Name(vers.Name);
                }
            }
            DbResources.CaboodleVersionKO = CaboodleVersionKO;
            class GalleryApi extends SingleKeyedResource {
                constructor(id, name, warning) {
                    super(id);
                    this.Name = "";
                    this.Warning = "";
                    this.Name = name;
                    this.Warning = warning;
                }
            }
            DbResources.GalleryApi = GalleryApi;
            class GalleryApiKO extends SingleKeyedObservableResource {
                constructor(api) {
                    super(api);
                    this.Id = ko.observable(0);
                    this.Name = ko.observable("");
                    this.Warning = ko.observable("");
                    if (api == null) {
                        return;
                    }
                    this.Id(api.Id);
                    this.Name(api.Name);
                    this.Warning(api.Warning);
                }
            }
            DbResources.GalleryApiKO = GalleryApiKO;
            class Screenshot {
                constructor(id, imageData, caption, mimeType, width, height, order) {
                    this.Id = 0;
                    this.ImageData = "";
                    this.Caption = "";
                    this.MimeType = "";
                    this.Width = "";
                    this.Height = "";
                    this.Order = 0;
                    if (id)
                        this.Id = id;
                    if (imageData)
                        this.ImageData = imageData;
                    if (caption)
                        this.Caption = caption;
                    if (mimeType)
                        this.MimeType = mimeType;
                    if (width)
                        this.Width = width;
                    if (height)
                        this.Height = height;
                    if (order)
                        this.Order = order;
                }
            }
            DbResources.Screenshot = Screenshot;
            class ScreenshotKO {
                constructor(shot) {
                    this.Id = ko.observable(0);
                    this.ImageData = ko.observable("");
                    this.Caption = ko.observable("");
                    this.MimeType = ko.observable("");
                    this.Width = ko.observable("");
                    this.Height = ko.observable("");
                    this.Order = ko.observable(0);
                    if (shot == null) {
                        return;
                    }
                    this.Id(shot.Id);
                    this.ImageData(shot.ImageData);
                    this.Caption(shot.Caption);
                    this.MimeType(shot.MimeType);
                    this.Width(shot.Width);
                    this.Height(shot.Height);
                    this.Order(shot.Order);
                }
                ;
            }
            DbResources.ScreenshotKO = ScreenshotKO;
            class FeatureSet extends SingleKeyedResource {
                constructor(id, name, description) {
                    super(id);
                    this.Id = 0;
                    this.Name = "";
                    this.Description = "";
                    if (name)
                        this.Name = name;
                    if (description)
                        this.Description = description;
                }
            }
            DbResources.FeatureSet = FeatureSet;
            class FeatureSetKO extends SingleKeyedObservableResource {
                constructor(feature) {
                    super(feature);
                    this.Id = ko.observable(0);
                    this.Name = ko.observable("");
                    this.Description = ko.observable("");
                    this.ExecuteAjaxToSaveResource = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "api\FeatureSet\Save", false, this, (data, textStatus, jqXHR) => {
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "api\FeatureSet\Save");
                        }, 3000);
                    };
                    this.OnValidateProperties = () => {
                        let result = new ResourcePropertyValidationResultCollection(!this.CanCollapse() || !this.IsReadOnly());
                        // add logic for verification
                        if (!this.Name || this.Name.length == 0) {
                            result.AddPropertyValidationResult("txtFeatureSet" + this.Id(), true, false, "Name is required.");
                        }
                        return result;
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Name = this.Name();
                        this.Resource.Description = this.Description();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Name(this.Resource.Name);
                        this.Description(this.Resource.Description);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.Description() != this.Resource.Description)) {
                            return true;
                        }
                        return false;
                    }, this);
                    if (feature == null) {
                        return;
                    }
                    this.Id(feature.Id);
                    this.Name(feature.Name);
                    this.Description(feature.Description);
                }
                ;
            }
            DbResources.FeatureSetKO = FeatureSetKO;
            class API_Internal extends DbResources.SingleKeyedResource {
                constructor(id, name, documentId, apps, hasAccess, hasTierAccess, isClarity) {
                    super(id);
                    this.Name = "";
                    this.DocumentId = 0;
                    this.Apps = [];
                    this.HasAccess = false;
                    this.HasTierAccess = false;
                    this.IsClarity = false;
                    if (name)
                        this.Name = name;
                    if (documentId)
                        this.DocumentId = documentId;
                    if (apps)
                        this.Apps = apps;
                    if (hasAccess)
                        this.HasAccess = hasAccess;
                    if (hasTierAccess)
                        this.HasTierAccess = hasTierAccess;
                    if (isClarity)
                        this.IsClarity = isClarity;
                }
            }
            DbResources.API_Internal = API_Internal;
            class API_InternalKO extends DbResources.SingleKeyedObservableResource {
                constructor(api) {
                    super(api);
                    this.Name = super.CreateAndRegisterValidatedKOProperty("");
                    this.DocumentId = super.CreateAndRegisterValidatedKOProperty(0);
                    this.Apps = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.HasAccess = super.CreateAndRegisterValidatedKOProperty(false);
                    this.HasTierAccess = super.CreateAndRegisterValidatedKOProperty(false);
                    this.IsClarity = super.CreateAndRegisterValidatedKOProperty(false);
                    this.OrgName = super.CreateAndRegisterValidatedKOProperty("");
                    this.Override = super.CreateAndRegisterValidatedKOProperty(false);
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Name: this.Name(),
                            DocumentId: this.DocumentId(),
                            Apps: this.Apps(),
                            HasAccess: this.HasAccess(),
                            HasTierAccess: this.HasTierAccess(),
                            IsClarity: this.IsClarity()
                        };
                    };
                    this.ConvertToJSList = () => {
                        return {
                            Id: this.Id(),
                            Name: this.Name(),
                            DocumentId: this.DocumentId(),
                            Apps: this.Apps(),
                            HasAccess: this.HasAccess(),
                            HasTierAccess: this.HasTierAccess(),
                            IsClarity: this.IsClarity()
                        };
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Name = this.Name();
                        this.Resource.DocumentId = this.DocumentId();
                        this.Resource.Apps = this.Apps();
                        this.Resource.HasAccess = this.HasAccess();
                        this.Resource.HasTierAccess = this.HasTierAccess();
                        this.Resource.IsClarity = this.IsClarity();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Name(this.Resource.Name);
                        this.Apps(this.Resource.Apps);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.Apps() != this.Resource.Apps)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.HasUnusedAccess = ko.computed(() => {
                        if (this.Apps == null) {
                            return false;
                        }
                        return (this.HasAccess() && this.Apps().length == 0);
                    }, this);
                    this.AppNamesCSV = ko.computed(() => {
                        return this.Apps().join(', ');
                    }, this);
                    this.AppNamesCSVOrUnusedAccess = ko.computed(() => {
                        if (this.HasUnusedAccess()) {
                            return "Not in use (should this be revoked?)";
                        }
                        return this.AppNamesCSV();
                    }, this);
                    if (api == null) {
                        return;
                    }
                    this.Id(api.Id || -1);
                    this.Name(api.Name || "");
                    this.DocumentId(api.DocumentId || 0);
                    this.Apps(api.Apps || []);
                    this.HasAccess(api.HasAccess || false);
                    this.HasTierAccess(api.HasTierAccess || false);
                    this.IsClarity(api.IsClarity || false);
                }
                ;
            }
            DbResources.API_InternalKO = API_InternalKO;
            class AppDownload_Internal extends DbResources.SingleKeyedResource {
                constructor(id, name, orgName, downloadApprovedStatus, installStatus, wasDownloadEverApproved, wasNonProdEverApproved) {
                    super(id);
                    this.Name = "";
                    this.OrgName = "";
                    this.DownloadApprovedStatus = DownloadApprovedStatus.Unapproved;
                    this.InstallStatus = InstallStatus.NotStarted;
                    this.WasDownloadEverApproved = false;
                    this.WasNonProdEverApproved = false;
                    if (name)
                        this.Name = name;
                    if (orgName)
                        this.OrgName = orgName;
                    if (downloadApprovedStatus)
                        this.DownloadApprovedStatus = downloadApprovedStatus;
                    if (installStatus)
                        this.InstallStatus = installStatus;
                    if (wasDownloadEverApproved)
                        this.WasDownloadEverApproved = wasDownloadEverApproved;
                    if (wasNonProdEverApproved)
                        this.WasNonProdEverApproved = wasNonProdEverApproved;
                }
            }
            DbResources.AppDownload_Internal = AppDownload_Internal;
            class AppDownload_InternalKO extends DbResources.SingleKeyedObservableResource {
                constructor(app) {
                    super(app);
                    this.Name = super.CreateAndRegisterValidatedKOProperty("");
                    this.OrgName = super.CreateAndRegisterValidatedKOProperty("");
                    this.DownloadApprovedStatus = super.CreateAndRegisterValidatedKOProperty(DownloadApprovedStatus.Unapproved);
                    this.InstallStatus = super.CreateAndRegisterValidatedKOProperty(InstallStatus.NotStarted);
                    this.EditableInstallStatus = super.CreateAndRegisterValidatedKOProperty(InstallStatus.NotStarted);
                    this.WasDownloadEverApproved = super.CreateAndRegisterValidatedKOProperty(false);
                    this.WasNonProdEverApproved = super.CreateAndRegisterValidatedKOProperty(false);
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Name: this.Name(),
                            OrgName: this.OrgName(),
                            DownloadApprovedStatus: this.DownloadApprovedStatus(),
                            InstallStatus: this.InstallStatus(),
                            WasDownloadEverApproved: this.WasDownloadEverApproved(),
                            WasNonProdEverApproved: this.WasNonProdEverApproved()
                        };
                    };
                    this.ConvertToJSList = () => {
                        return {
                            Id: this.Id(),
                            Name: this.Name(),
                            OrgName: this.OrgName(),
                            DownloadApprovedStatus: this.DownloadApprovedStatus(),
                            InstallStatus: this.InstallStatus(),
                            WasDownloadEverApproved: this.WasDownloadEverApproved(),
                            WasNonProdEverApproved: this.WasNonProdEverApproved()
                        };
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Name = this.Name();
                        this.Resource.OrgName = this.OrgName();
                        this.Resource.DownloadApprovedStatus = this.DownloadApprovedStatus();
                        this.Resource.InstallStatus = this.InstallStatus();
                        this.Resource.WasDownloadEverApproved = this.WasDownloadEverApproved();
                        this.Resource.WasNonProdEverApproved = this.WasNonProdEverApproved();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Name(this.Resource.Name);
                        this.OrgName(this.Resource.OrgName);
                        this.DownloadApprovedStatus(this.Resource.DownloadApprovedStatus);
                        this.InstallStatus(this.Resource.InstallStatus);
                        this.EditableInstallStatus(this.InstallStatus());
                        this.WasDownloadEverApproved(this.WasDownloadEverApproved());
                        this.WasNonProdEverApproved(this.WasNonProdEverApproved());
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.OrgName() != this.Resource.OrgName) ||
                            (this.DownloadApprovedStatus() != this.Resource.DownloadApprovedStatus) ||
                            (this.InstallStatus() != this.Resource.InstallStatus) ||
                            (this.WasDownloadEverApproved() != this.Resource.WasDownloadEverApproved) ||
                            (this.WasNonProdEverApproved() != this.Resource.WasNonProdEverApproved)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.IsDownloadApproved = ko.computed(() => {
                        if (!this.DownloadApprovedStatus) {
                            return false;
                        }
                        return this.DownloadApprovedStatus() == DownloadApprovedStatus.Approved;
                    }, this);
                    this.IsDownloadDeclined = ko.computed(() => {
                        if (!this.DownloadApprovedStatus) {
                            return false;
                        }
                        return this.DownloadApprovedStatus() == DownloadApprovedStatus.Declined;
                    }, this);
                    this.IsInstallLive = ko.computed(() => {
                        if (!this.InstallStatus) {
                            return false;
                        }
                        return this.InstallStatus() == InstallStatus.Live;
                    }, this);
                    this.IsInstallNotStarted = ko.computed(() => {
                        if (!this.DownloadApprovedStatus) {
                            return false;
                        }
                        return this.InstallStatus() == InstallStatus.NotStarted;
                    }, this);
                    this.DownloadApprovedStatusString = ko.computed(() => {
                        if (!this.DownloadApprovedStatus) {
                            return "";
                        }
                        return Epic.AppOrchard.Util.GetEnumValueName(this.DownloadApprovedStatus(), DownloadApprovedStatus);
                    }, this);
                    this.InstallStatusString = ko.computed(() => {
                        if (!this.InstallStatus) {
                            return "";
                        }
                        else if (this.InstallStatus() == null) {
                            return "Not set";
                        }
                        return Epic.AppOrchard.Helpers.PrettifyPascalCase(Epic.AppOrchard.Util.GetEnumValueName(this.InstallStatus(), InstallStatus));
                    }, this);
                    this.UnsavedInstallStatusChange = ko.computed(() => {
                        if (!this.InstallStatus || !this.EditableInstallStatus || (this.InstallStatus() == null && this.EditableInstallStatus() == "null")) {
                            return false;
                        }
                        return !(this.InstallStatus() == this.EditableInstallStatus());
                    }, this);
                    if (app == null) {
                        return;
                    }
                    this.Id(app.Id || -1);
                    this.Name(app.Name || "");
                    this.OrgName(app.OrgName || "");
                    this.DownloadApprovedStatus(app.DownloadApprovedStatus || DownloadApprovedStatus.Unapproved);
                    this.InstallStatus(app.InstallStatus);
                    this.EditableInstallStatus(this.InstallStatus());
                    this.WasDownloadEverApproved(app.WasDownloadEverApproved);
                    this.WasNonProdEverApproved(app.WasNonProdEverApproved);
                }
                ;
            }
            DbResources.AppDownload_InternalKO = AppDownload_InternalKO;
            class KitImportSection {
            }
            DbResources.KitImportSection = KitImportSection;
            class AuthorizedApiKitDataModelColumnDefinitionKO {
                constructor(data) {
                    this.Id = ko.observable(-1);
                    this.TableEtlName = ko.observable("");
                    this.TableColumnName = ko.observable("");
                    this.Description = ko.observable("");
                    this.CaboodleDataType = ko.observable("");
                    this.AllowNull = ko.observable(false);
                    this.DefaultValue = ko.observable("");
                    this.DeleteValue = ko.observable("");
                    this.ForeignKey = ko.observable("");
                    this.Type2 = ko.observable(false);
                    this.Id(data.Id);
                    this.TableEtlName(data.TableEtlName);
                    this.TableColumnName(data.TableColumnName);
                    this.Description(data.Description);
                    this.CaboodleDataType(data.CaboodleDataType);
                    this.AllowNull(data.AllowNull);
                    this.DefaultValue(data.DefaultValue);
                    this.DeleteValue(data.DeleteValue);
                    this.ForeignKey(data.ForeignKey);
                    this.Type2(data.Type2);
                }
            }
            DbResources.AuthorizedApiKitDataModelColumnDefinitionKO = AuthorizedApiKitDataModelColumnDefinitionKO;
            //#region ContentSchema
            class ContentSchema extends SingleKeyedResource {
                constructor(id, name, isPublished, isInUse, versionList, epicVersions, contentSchemaDocumentList) {
                    super(id);
                    this.Name = "";
                    this.IsPublished = false;
                    this.IsInUse = false;
                    this.VersionList = null;
                    this.EpicVersions = null;
                    this.ContentSchemaDocumentList = null;
                    if (name)
                        this.Name = name;
                    if (isPublished)
                        this.IsPublished = isPublished;
                    if (isInUse)
                        this.IsInUse = isInUse;
                    if (versionList)
                        this.VersionList = versionList;
                    if (epicVersions)
                        this.EpicVersions = epicVersions;
                    if (contentSchemaDocumentList)
                        this.ContentSchemaDocumentList = contentSchemaDocumentList;
                }
            }
            DbResources.ContentSchema = ContentSchema;
            class ContentSchemaKO extends SingleKeyedObservableResource {
                constructor(schema) {
                    super(schema);
                    this.Name = super.CreateAndRegisterValidatedKOProperty("");
                    this.IsPublished = super.CreateAndRegisterValidatedKOProperty(false);
                    this.IsInUse = super.CreateAndRegisterValidatedKOProperty(false);
                    this.VersionList = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.EpicVersions = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.ContentSchemaDocumentList = super.CreateAndRegisterValidatedKOArrayProperty();
                    if (schema == null) {
                        return;
                    }
                    this.Id(schema.Id);
                    this.Name(schema.Name);
                    this.IsPublished(schema.IsPublished);
                    this.IsInUse(schema.IsInUse);
                    this.EpicVersions(schema.EpicVersions);
                    if (schema.VersionList != null) {
                        for (var x = 0; x < schema.VersionList.length; x++) {
                            this.VersionList.push(schema.VersionList[x]);
                        }
                    }
                    if (schema.ContentSchemaDocumentList != null) {
                        for (var x = 0; x < schema.ContentSchemaDocumentList.length; x++) {
                            let schemaContent = schema.ContentSchemaDocumentList[x];
                            let schemaContentKO = new ContentSchemaDocumentKO(schemaContent);
                            this.ContentSchemaDocumentList.push(schemaContentKO);
                        }
                    }
                }
            }
            DbResources.ContentSchemaKO = ContentSchemaKO;
            class VersionRange {
                constructor(startVersion, endVersion) {
                    this.StartVersion = null;
                    this.EndVersion = null;
                    if (startVersion)
                        this.StartVersion = startVersion;
                    if (endVersion)
                        this.EndVersion = endVersion;
                }
            }
            DbResources.VersionRange = VersionRange;
            class VersionDocument {
                constructor(versionId, versionDocumentList) {
                    this.VersionId = 0;
                    this.VersionDocumentList = null;
                    if (versionId)
                        this.VersionId = versionId;
                    if (versionDocumentList)
                        this.VersionDocumentList = versionDocumentList;
                }
            }
            DbResources.VersionDocument = VersionDocument;
            class ContentSchemaDocument extends SingleKeyedResource {
                constructor(id, name, description, version, namespace, fileGroups) {
                    super(id);
                    this.Name = "";
                    this.Description = "";
                    this.Version = 0;
                    this.Namespace = "";
                    this.FileGroups = null;
                    if (name)
                        this.Name = name;
                    if (description)
                        this.Description = description;
                    if (version)
                        this.Version = version;
                    if (namespace)
                        this.Namespace = namespace;
                    if (fileGroups)
                        this.FileGroups = fileGroups;
                }
            }
            DbResources.ContentSchemaDocument = ContentSchemaDocument;
            class ContentSchemaDocumentKO extends SingleKeyedObservableResource {
                constructor(contentSchemaDocument) {
                    super(contentSchemaDocument);
                    this.Name = super.CreateAndRegisterValidatedKOProperty("");
                    this.Description = super.CreateAndRegisterValidatedKOProperty("");
                    this.Version = super.CreateAndRegisterValidatedKOProperty(0);
                    this.Namespace = super.CreateAndRegisterValidatedKOProperty("");
                    this.FileGroups = super.CreateAndRegisterValidatedKOArrayProperty();
                    this.DisplayName = ko.computed(() => {
                        if (this.Name().length > 150) {
                            return this.Name().slice(0, 150) + "...";
                        }
                        return this.Name();
                    }, this);
                    if (contentSchemaDocument == null) {
                        return;
                    }
                    this.Id(contentSchemaDocument.Id);
                    this.Name(contentSchemaDocument.Name);
                    this.Description(contentSchemaDocument.Description);
                    this.Version(contentSchemaDocument.Version);
                    this.Namespace(contentSchemaDocument.Namespace);
                    if (contentSchemaDocument.FileGroups) {
                        for (var i = 0; i < contentSchemaDocument.FileGroups.length; i++) {
                            let currentDocument = contentSchemaDocument.FileGroups[i];
                            this.FileGroups.push(currentDocument);
                        }
                    }
                }
            }
            DbResources.ContentSchemaDocumentKO = ContentSchemaDocumentKO;
            class ContentSchemaFileGroup {
                constructor(files, isXSDFileGroup, isXMLFileGroup, isPDFFileGroup) {
                    this.Files = null;
                    this.IsXSDFileGroup = false;
                    this.IsXMLFileGroup = false;
                    this.IsPDFFileGroup = false;
                    if (files)
                        this.Files = files;
                    if (isXSDFileGroup)
                        this.IsXSDFileGroup = isXSDFileGroup;
                    if (isXMLFileGroup)
                        this.IsXMLFileGroup = isXMLFileGroup;
                    if (isPDFFileGroup)
                        this.IsPDFFileGroup = isPDFFileGroup;
                }
            }
            DbResources.ContentSchemaFileGroup = ContentSchemaFileGroup;
            //#endregion
            //#region Email Templates
            class EmailTemplate extends SingleKeyedResource {
                constructor(id, name, subject, htmlBody, textBody, toAddrs, fromAddrs, ccAddrs, bccAddrs) {
                    super(id);
                    this.Name = "";
                    this.Subject = "";
                    this.HtmlBody = "";
                    this.TextBody = "";
                    this.To = "";
                    this.From = "";
                    this.CC = "";
                    this.BCC = "";
                    if (name)
                        this.Name = name;
                    if (subject)
                        this.Subject = subject;
                    if (htmlBody)
                        this.HtmlBody = htmlBody;
                    if (textBody)
                        this.TextBody = textBody;
                    if (toAddrs)
                        this.To = toAddrs;
                    if (fromAddrs)
                        this.From = fromAddrs;
                    if (ccAddrs)
                        this.CC = ccAddrs;
                    if (bccAddrs)
                        this.BCC = bccAddrs;
                }
            }
            DbResources.EmailTemplate = EmailTemplate;
            class EmailTemplateKO extends SingleKeyedObservableResource {
                constructor(authorizedUser) {
                    super(authorizedUser);
                    this.Name = super.CreateAndRegisterValidatedKOProperty("");
                    this.Subject = super.CreateAndRegisterValidatedKOProperty("");
                    this.HtmlBody = super.CreateAndRegisterValidatedKOProperty("");
                    this.TextBody = super.CreateAndRegisterValidatedKOProperty("");
                    this.To = super.CreateAndRegisterValidatedKOProperty("");
                    this.From = super.CreateAndRegisterValidatedKOProperty("");
                    this.CC = super.CreateAndRegisterValidatedKOProperty("");
                    this.BCC = super.CreateAndRegisterValidatedKOProperty("");
                    this.ExecuteAjaxToSaveResource = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "Account/EmailTemplate", false, {
                            Id: this.Id(),
                            Name: this.Name(),
                            Subject: this.Subject(),
                            HtmlBody: this.HtmlBody(),
                            TextBody: this.TextBody(),
                            To: this.To(),
                            From: this.From(),
                            CC: this.CC(),
                            BCC: this.BCC()
                        }, (data, textStatus, jqXHR) => {
                            this.IsReadOnly(true);
                            Epic.AppOrchard.Util.Alert("Success", "Changes Saved!");
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "Account/EmailTemplate");
                        }, 3000, false, this);
                    };
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Name: this.Name(),
                            Subject: this.Subject(),
                            HtmlBody: this.HtmlBody(),
                            TextBody: this.TextBody(),
                            To: this.To(),
                            From: this.From(),
                            CC: this.CC(),
                            BCC: this.BCC()
                        };
                    };
                    this.OnValidateProperties = () => {
                        let result = new ResourcePropertyValidationResultCollection(!this.CanCollapse() || !this.IsReadOnly());
                        // add logic for verification
                        result.AddPropertyValidationResult("txtEmailTemplateName" + this.Id(), Epic.AppOrchard.Util.IsNullOrEmpty(this.Name()), false, "Name is required.");
                        result.AddPropertyValidationResult("txtEmailTemplateSubject" + this.Id(), Epic.AppOrchard.Util.IsNullOrEmpty(this.Subject()), false, "Subject is required.");
                        result.AddPropertyValidationResult("txtEmailTemplateTextBody" + this.Id(), Epic.AppOrchard.Util.IsNullOrEmpty(this.TextBody()), false, "TextBody is required.");
                        //result.AddPropertyValidationResult("txtOrganizationUserPassword" + this.Id(), false, false, "Password is required.");
                        return result;
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Name = this.Name();
                        this.Resource.Subject = this.Subject();
                        this.Resource.HtmlBody = this.HtmlBody();
                        this.Resource.TextBody = this.TextBody();
                        this.Resource.To = this.To();
                        this.Resource.From = this.From();
                        this.Resource.CC = this.CC();
                        this.Resource.BCC = this.BCC();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Name(this.Resource.Name);
                        this.Subject(this.Resource.Subject);
                        this.HtmlBody(this.Resource.HtmlBody);
                        this.TextBody(this.Resource.TextBody);
                        this.To(this.Resource.To);
                        this.From(this.Resource.From);
                        this.CC(this.Resource.CC);
                        this.BCC(this.Resource.BCC);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Name() != this.Resource.Name) ||
                            (this.Subject() != this.Resource.Subject) ||
                            (this.HtmlBody() != this.Resource.HtmlBody) ||
                            (this.TextBody() != this.Resource.TextBody) ||
                            (this.To() != this.Resource.To) ||
                            (this.From() != this.Resource.From) ||
                            (this.CC() != this.Resource.CC) ||
                            (this.BCC() != this.Resource.BCC)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.EmailRaw = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "/Account/TestEmailRaw", false, this.ConvertToJS(), () => {
                            Epic.AppOrchard.Util.Alert("Success", "Test Email Sent!");
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "/Account/TestEmailRaw");
                        });
                    };
                    this.EmailHtml = () => {
                        Epic.AppOrchard.API.ExecuteAjax(AppOrchard.HttpMethod.POST, "/Account/TestEmailHtml", false, this.ConvertToJS(), () => {
                            Epic.AppOrchard.Util.Alert("Success", "Test Email Sent!");
                        }, (jqXHR, textStatus, errorThrown) => {
                            Epic.AppOrchard.Util.LogJSEvent(false, textStatus, errorThrown, "/Account/TestEmailHtml");
                        });
                    };
                    this.BeginEdit = () => {
                        this.IsExpanded(true);
                        this.IsReadOnly(false);
                    };
                    this.EndEdit = (save) => {
                        if (!save) {
                            this.Revert();
                            return;
                        }
                        this.Save();
                    };
                    if (authorizedUser == null) {
                        return;
                    }
                    this.Id(authorizedUser.Id);
                    this.Name(authorizedUser.Name);
                    this.Subject(authorizedUser.Subject);
                    this.HtmlBody(authorizedUser.HtmlBody);
                    this.TextBody(authorizedUser.TextBody);
                    this.To(authorizedUser.To);
                    this.From(authorizedUser.From);
                    this.CC(authorizedUser.CC);
                    this.BCC(authorizedUser.BCC);
                }
            }
            DbResources.EmailTemplateKO = EmailTemplateKO;
            class EmailTemplateTokenKO {
                constructor(name, token, description) {
                    this.Name = ko.observable("");
                    this.Token = ko.observable("");
                    this.Description = ko.observable("");
                    this.IsSelected = ko.observable(false);
                    this.Name(name);
                    this.Token(token);
                    this.Description(description);
                }
            }
            DbResources.EmailTemplateTokenKO = EmailTemplateTokenKO;
            class EmailTemplateTokens {
                static Add(name, token, description) {
                    EmailTemplateTokens.Items.push(new EmailTemplateTokenKO(name, token, description));
                }
                static Paste(a, b, c, d) {
                    var elm = Epic.AppOrchard.DbResources.EmailTemplateTokens.Focus;
                    if (!elm) {
                        return;
                    }
                    elm.focus();
                    var start = elm.selectionStart;
                    var end = elm.selectionEnd;
                    elm.value = elm.value.substring(0, start) + a.Token() + elm.value.substring(end, elm.value.length);
                }
                static OnFocus(a, b, c) {
                    var elm = b.currentTarget;
                    Epic.AppOrchard.DbResources.EmailTemplateTokens.Focus = elm;
                    if (elm.type == 'textarea') {
                        Epic.AppOrchard.Util.TextAreaFocus(a, b);
                    }
                }
            }
            EmailTemplateTokens.Items = ko.observableArray([]);
            EmailTemplateTokens.Focus = null;
            DbResources.EmailTemplateTokens = EmailTemplateTokens;
            //#endregion
            //#region ExtendedContent
            class ExtendedContent extends SingleKeyedResource {
                constructor(id, title, contentType) {
                    super(id);
                    this.Title = "";
                    this.ContentType = "";
                    if (title)
                        this.Title = title;
                    if (contentType)
                        this.ContentType = contentType;
                }
            }
            DbResources.ExtendedContent = ExtendedContent;
            class ExtendedContentKO extends SingleKeyedObservableResource {
                constructor(obj) {
                    super(obj);
                    this.Title = super.CreateAndRegisterValidatedKOProperty("");
                    this.ContentType = super.CreateAndRegisterValidatedKOProperty("");
                    this.ExecuteAjaxToSaveResource = () => {
                        throw "NotImplementedException";
                    };
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Title: this.Title(),
                            ContentType: this.ContentType()
                        };
                    };
                    this.OnValidateProperties = () => {
                        let result = new ResourcePropertyValidationResultCollection(!this.CanCollapse() || !this.IsReadOnly());
                        // add logic for verification
                        //result.AddPropertyValidationResult("txtEmailTemplateName" + this.Id(), Epic.AppOrchard.Util.IsNullOrEmpty(this.Title()), false, "Name is required.");
                        //result.AddPropertyValidationResult("txtEmailTemplateSubject" + this.Id(), Epic.AppOrchard.Util.IsNullOrEmpty(this.ContentType()), false, "Subject is required.");
                        //result.AddPropertyValidationResult("txtOrganizationUserPassword" + this.Id(), false, false, "Password is required.");
                        return result;
                    };
                    this.OnSaved = () => {
                        this.Resource.Id = this.Id();
                        this.Resource.Title = this.Title();
                        this.Resource.ContentType = this.ContentType();
                    };
                    this.OnRevert = () => {
                        this.Id(this.Resource.Id);
                        this.Title(this.Resource.Title);
                        this.ContentType(this.Resource.ContentType);
                    };
                    this.IsDirty = ko.computed(() => {
                        if (this.Resource == null) {
                            return false;
                        }
                        if ((this.Id() != this.Resource.Id) ||
                            (this.Title() != this.Resource.Title) ||
                            (this.ContentType() != this.Resource.ContentType)) {
                            return true;
                        }
                        return false;
                    }, this);
                    this.BeginEdit = () => {
                        this.IsExpanded(true);
                        this.IsReadOnly(false);
                    };
                    this.EndEdit = (save) => {
                        //this.IsExpanded(true);
                        //this.IsReadOnly(false);
                        if (!save) {
                            this.Revert();
                            return;
                        }
                        this.Save();
                    };
                    if (obj == null) {
                        return;
                    }
                    this.Id(obj.Id);
                    this.Title(obj.Title);
                    this.ContentType(obj.ContentType);
                }
            }
            DbResources.ExtendedContentKO = ExtendedContentKO;
            //#endregion
            //#region Content Validation
            class ContentValidation extends SingleKeyedResource {
                constructor(id, fileName, contentSchemaId, contentSchemaName, documentVersion, userName, uploadOn, status, messageTitle, message, isMessageExpanded, canDelete) {
                    super(id);
                    this.FileName = "";
                    this.ContentSchemaId = 0;
                    this.ContentSchemaName = "";
                    this.DocumentVersion = "";
                    this.UserName = "";
                    this.UploadOn = "";
                    this.Status = ContentValidationStatus.Any;
                    this.MessageTitle = "";
                    this.Message = "";
                    this.IsMessageExpanded = false;
                    this.CanDelete = false;
                    if (fileName)
                        this.FileName = fileName;
                    if (contentSchemaId)
                        this.ContentSchemaId = contentSchemaId;
                    if (contentSchemaName)
                        this.ContentSchemaName = contentSchemaName;
                    if (documentVersion)
                        this.DocumentVersion = documentVersion;
                    if (userName)
                        this.UserName = userName;
                    if (uploadOn)
                        this.UploadOn = uploadOn;
                    if (status)
                        this.Status = status;
                    if (messageTitle)
                        this.MessageTitle = messageTitle;
                    if (message)
                        this.Message = message;
                    if (isMessageExpanded)
                        this.IsMessageExpanded = isMessageExpanded;
                    if (canDelete)
                        this.CanDelete = canDelete;
                }
            }
            DbResources.ContentValidation = ContentValidation;
            class ContentValidationKO extends SingleKeyedObservableResource {
                constructor(contentValidation) {
                    super(contentValidation);
                    this.FileName = super.CreateAndRegisterValidatedKOProperty("");
                    this.ContentSchemaId = super.CreateAndRegisterValidatedKOProperty(0);
                    this.ContentSchemaName = super.CreateAndRegisterValidatedKOProperty("");
                    this.DocumentVersion = super.CreateAndRegisterValidatedKOProperty("");
                    this.UserName = super.CreateAndRegisterValidatedKOProperty("");
                    this.UploadOn = super.CreateAndRegisterValidatedKOProperty("");
                    this.Status = super.CreateAndRegisterValidatedKOProperty(ContentValidationStatus.Any);
                    this.MessageTitle = super.CreateAndRegisterValidatedKOProperty("");
                    this.Message = super.CreateAndRegisterValidatedKOProperty("");
                    this.IsMessageExpanded = super.CreateAndRegisterValidatedKOProperty(false);
                    this.CanDelete = super.CreateAndRegisterValidatedKOProperty(false);
                    this.IsInProgress = ko.computed(() => {
                        return this.Status() == ContentValidationStatus.InProgress;
                    }, this);
                    this.IsDone = ko.computed(() => {
                        return this.Status() == ContentValidationStatus.Done;
                    }, this);
                    this.IsError = ko.computed(() => {
                        return this.Status() == ContentValidationStatus.Error;
                    }, this);
                    this.GetIconTitle = ko.computed(() => {
                        switch (this.Status()) {
                            case ContentValidationStatus.Done:
                                return "Success";
                            case ContentValidationStatus.InProgress:
                                return "In progress";
                            case ContentValidationStatus.Error:
                                return "Error";
                            default:
                                return "";
                        }
                    }, this);
                    this.FileNameForDisplay = ko.computed(() => {
                        if (this.FileName().length > 50) {
                            return this.FileName().slice(0, 50) + "...";
                        }
                        return this.FileName();
                    }, this);
                    this.FileName(contentValidation.FileName);
                    this.ContentSchemaId(contentValidation.ContentSchemaId);
                    this.ContentSchemaName(contentValidation.ContentSchemaName);
                    this.DocumentVersion(contentValidation.DocumentVersion);
                    this.UserName(contentValidation.UserName);
                    this.UploadOn(contentValidation.UploadOn);
                    this.Status(contentValidation.Status);
                    this.MessageTitle(contentValidation.MessageTitle);
                    this.Message(contentValidation.Message);
                    this.IsMessageExpanded(contentValidation.IsMessageExpanded);
                    this.CanDelete(contentValidation.CanDelete);
                }
                ToggleExpandMessage() {
                    if (!this.IsMessageExpanded()) {
                        this.IsMessageExpanded(true);
                    }
                    else {
                        this.IsMessageExpanded(false);
                    }
                }
            }
            DbResources.ContentValidationKO = ContentValidationKO;
            class KeyValuePairHelper {
                static GetValues(list) {
                    if (!list || list.length == 0) {
                        return [];
                    }
                    return list.map((item) => {
                        return item.Value;
                    });
                }
                static FindMatchingPairInArray(keyToMatch, array, caseInsensitive = false) {
                    if (caseInsensitive) {
                        keyToMatch = keyToMatch.toUpperCase();
                    }
                    for (var i = 0; i < array.length; i++) {
                        var currKey = array[i].Key;
                        if (caseInsensitive) {
                            currKey = currKey.toUpperCase();
                        }
                        if (currKey == keyToMatch) {
                            return array[i];
                        }
                    }
                    return null;
                }
                static FindMatchingPairInKOArray(keyToMatch, koArray, caseInsensitive = false) {
                    if (caseInsensitive) {
                        keyToMatch = keyToMatch.toUpperCase();
                    }
                    for (var i = 0; i < koArray().length; i++) {
                        var currKey = koArray()[i].Key;
                        if (caseInsensitive) {
                            currKey = currKey.toUpperCase();
                        }
                        if (currKey == keyToMatch) {
                            return koArray()[i];
                        }
                    }
                    return null;
                }
                static SortByStringKeys(kvp1, kvp2) {
                    return kvp1.Key.localeCompare(kvp2.Key);
                }
            }
            DbResources.KeyValuePairHelper = KeyValuePairHelper;
            class NamedObject extends SingleKeyedResource {
                constructor(id, name) {
                    super(id);
                    this.Id = 0;
                    this.Name = "";
                    if (name)
                        this.Name = name;
                }
            }
            DbResources.NamedObject = NamedObject;
            class TCDocumentInfo {
            }
            DbResources.TCDocumentInfo = TCDocumentInfo;
            class TCDocumentInfoKO {
                constructor(tcDoc) {
                    this.DocumentId = ko.observable(0);
                    this.DocumentName = ko.observable("");
                    this.ExtendedContentId = ko.observable(0);
                    this.EpicVersion = ko.observable("");
                    this.MinEpicVersion = ko.observable("");
                    this.EpicCode = ko.observable(0);
                    this.MasterFiles = ko.observable("");
                    if (tcDoc) {
                        this.DocumentId(tcDoc.DocumentId);
                        this.DocumentName(tcDoc.DocumentName);
                        this.ExtendedContentId(tcDoc.ExtendedContentId);
                        this.EpicVersion(tcDoc.EpicVersion);
                        this.MinEpicVersion(tcDoc.MinEpicVersion);
                        this.EpicCode(tcDoc.EpicCode);
                        this.MasterFiles(tcDoc.MasterFiles);
                    }
                }
            }
            DbResources.TCDocumentInfoKO = TCDocumentInfoKO;
            class ReviewPrompt extends DbResources.SingleKeyedResource {
                constructor(id, text, response, orderNumber) {
                    super(id);
                    if (text)
                        this.Text = text;
                    if (response)
                        this.Response = response;
                    if (orderNumber)
                        this.OrderNumber = orderNumber;
                }
            }
            ReviewPrompt.SortPromptsAsc = function (a, b) {
                return a.OrderNumber - b.OrderNumber;
            };
            DbResources.ReviewPrompt = ReviewPrompt;
            class ReviewPromptKO extends DbResources.SingleKeyedObservableResource {
                constructor(Prompt) {
                    super(Prompt);
                    this.Text = ko.observable("");
                    this.Response = ko.observable(null); //Note, we aren't setting this to DbResources.ReviewResponseValue.Null on purpose.  Doing so would make the Not applicable buttons lit on page load.  We only want them lit if the user directly clicks them.
                    this.OrderNumber = ko.observable(-1);
                    this.IsAnswered = ko.computed(() => {
                        if (this.Response == null || this.Response() == null) {
                            return false;
                        }
                        return this.Response() != DbResources.ReviewResponseValue.Null;
                    }, this);
                    this.IsNegativeResponse = ko.computed(() => {
                        if (this.Response == null || this.Response() == null) {
                            return false;
                        }
                        return this.Response() == DbResources.ReviewResponseValue.Negative;
                    }, this);
                    this.IsPositiveResponse = ko.computed(() => {
                        if (this.Response == null || this.Response() == null) {
                            return false;
                        }
                        return this.Response() == DbResources.ReviewResponseValue.Positive;
                    }, this);
                    this.ConvertToJS = () => {
                        return {
                            Id: this.Id(),
                            Text: this.Text(),
                            Response: this.Response(),
                            OrderNumber: this.OrderNumber()
                        };
                    };
                    if (Prompt == null) {
                        return;
                    }
                    this.Text(Prompt.Text || "");
                    this.Response(Prompt.Response || null); //Note, we aren't setting this to DbResources.ReviewResponseValue.Null on purpose.  Doing so would make the Not applicable buttons lit on page load.  We only want them lit if the user directly clicks them.
                    this.OrderNumber(Prompt.OrderNumber || -1);
                }
                NegativeClicked() {
                    if (this.Response() != DbResources.ReviewResponseValue.Negative) {
                        this.Response(DbResources.ReviewResponseValue.Negative);
                    }
                }
                PositiveClicked() {
                    if (this.Response() != DbResources.ReviewResponseValue.Positive) {
                        this.Response(DbResources.ReviewResponseValue.Positive);
                    }
                }
                NotApplicableClicked() {
                    if (this.Response() != DbResources.ReviewResponseValue.Null) {
                        this.Response(DbResources.ReviewResponseValue.Null);
                    }
                }
            }
            DbResources.ReviewPromptKO = ReviewPromptKO;
            class ResourceDocument {
                constructor(urlText, linkText, name, body) {
                    this.UrlText = "";
                    this.LinkText = "";
                    this.Name = "";
                    this.Body = "";
                    this.UrlText = urlText;
                    this.LinkText = linkText;
                    this.Name = name;
                    this.Body = body;
                }
            }
            DbResources.ResourceDocument = ResourceDocument;
            class NotImplementingNowModelKO {
                constructor(data, currentAppVersionId) {
                    this.UserName = ko.observable("");
                    this.Instant = ko.observable("");
                    this.PrivateReason = ko.observable("");
                    this.PublicReason = ko.observable("");
                    this.PrivateReasonEncoded = ko.observable("");
                    this.PublicReasonEncoded = ko.observable("");
                    this.NotifyInterestedUsers = ko.observable(true);
                    this.AppVersionId = ko.observable(-1);
                    this.CurrentAppVersionId = ko.observable(-1);
                    this.ErrorMessage = ko.observable("");
                    this.ExistsOnDb = ko.observable(false);
                    if (data) {
                        this.UserName(data.UserName);
                        const inst = new Date(data.Instant.toString());
                        this.Instant(inst.toLocaleDateString());
                        this.PrivateReason(data.PrivateReason);
                        this.PublicReason(data.PublicReason);
                        this.PrivateReasonEncoded(data.PrivateReasonEncoded);
                        this.PublicReasonEncoded(data.PublicReasonEncoded);
                        this.AppVersionId(data.AppVersionId);
                        this.CurrentAppVersionId(currentAppVersionId);
                        this.ExistsOnDb(true);
                    }
                }
                ReasonForTooltip(includePrivate) {
                    var content = "";
                    if (this.AppVersionId() !== this.CurrentAppVersionId()) {
                        content = "<i>This decision was documented for a previous app version.</i><br /><br />";
                    }
                    const hasPrivateReason = includePrivate && !Epic.AppOrchard.Util.IsNullOrEmpty(this.PrivateReason());
                    const includeUserName = includePrivate && !Epic.AppOrchard.Util.IsNullOrEmpty(this.UserName());
                    content += `Marked not implementing now on ${this.Instant()} ${(includeUserName ? 'by ' + Epic.AppOrchard.Helpers.EncodeText(this.UserName()) : '')}<br /><br />`;
                    if (hasPrivateReason) {
                        content += "<strong>Private reason: </strong>" + this.PrivateReasonEncoded();
                    }
                    if (!Epic.AppOrchard.Util.IsNullOrEmpty(this.PublicReason())) {
                        content += (hasPrivateReason ? "<br><br><strong>Public reason: </strong>" : "") + this.PublicReasonEncoded();
                    }
                    return content;
                }
                ConvertToJS() {
                    return {
                        UserName: this.UserName(),
                        Instant: new Date(this.Instant()),
                        PrivateReason: this.PrivateReason(),
                        PublicReason: this.PublicReason(),
                        AppVersionId: this.AppVersionId(),
                        Deleted: false,
                        // not needed for serialization
                        PrivateReasonEncoded: "",
                        PublicReasonEncoded: ""
                    };
                }
            }
            DbResources.NotImplementingNowModelKO = NotImplementingNowModelKO;
            class ContextTableRow {
            }
            DbResources.ContextTableRow = ContextTableRow;
            class ContextTableRowKO {
                constructor(contextTableRow) {
                    this.Key = ko.observable("");
                    this.Optionality = ko.observable(SubspaceOptionality.Optional);
                    this.Description = ko.observable("");
                    this.OptionalityString = ko.computed(() => {
                        if (this.Optionality == null) {
                            return "";
                        }
                        return Epic.AppOrchard.Util.GetEnumValueName(this.Optionality(), SubspaceOptionality);
                    }, this);
                    this.Key(contextTableRow.Key || "");
                    this.Optionality(contextTableRow.Optionality);
                    this.Description(contextTableRow.Description || "");
                }
                ProduceCells() {
                    var cells = [];
                    cells.push(this.Key());
                    cells.push(this.Optionality().toString());
                    cells.push(this.Description());
                    return cells;
                }
            }
            DbResources.ContextTableRowKO = ContextTableRowKO;
            class ColorTester {
                static CompareToWhite(color1Hex) {
                    let color2Hex = Color.WhiteHex;
                    let color1 = new Color(color1Hex);
                    let color2 = new Color(color2Hex);
                    let luminosity1 = color1.Luminosity();
                    let luminosity2 = color2.Luminosity();
                    return (Math.max(luminosity1, luminosity2) + ColorTester.luminosityAdder) / (Math.min(luminosity1, luminosity2) + ColorTester.luminosityAdder);
                }
                static Compare(color1Hex, color2Hex) {
                    let color1 = new Color(color1Hex);
                    let color2 = new Color(color2Hex);
                    let luminosity1 = color1.Luminosity();
                    let luminosity2 = color2.Luminosity();
                    return (Math.max(luminosity1, luminosity2) + ColorTester.luminosityAdder) / (Math.min(luminosity1, luminosity2) + ColorTester.luminosityAdder);
                }
            }
            ColorTester.luminosityAdder = 0.05;
            DbResources.ColorTester = ColorTester;
            class Color {
                constructor(hexValue) {
                    if (!hexValue)
                        return;
                    var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
                    hexValue = hexValue.replace(shorthandRegex, function (m, r, g, b) {
                        return r + r + g + g + b + b;
                    });
                    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexValue);
                    this.RawRed = parseInt(result[1], 16);
                    this.RawGreen = parseInt(result[2], 16);
                    this.RawBlue = parseInt(result[3], 16);
                }
                Luminosity() {
                    return Color.ChannelLuminence(this.RawRed) * Color.redRatio
                        + Color.ChannelLuminence(this.RawGreen) * Color.greenRatio
                        + Color.ChannelLuminence(this.RawBlue) * Color.blueRatio;
                }
                static ChannelLuminence(rawColorValue) {
                    let normalizedColorValue = this.normalizeRGB(rawColorValue);
                    if (normalizedColorValue <= Color.minChannelLuminenceRatio) {
                        return normalizedColorValue / Color.minChannelLuminenceDenominator;
                    }
                    else {
                        return Math.pow((normalizedColorValue + Color.luminenceNormalizedAdder) / Color.luminenceDenominator, Color.luminenceExponent);
                    }
                }
                static normalizeRGB(rawColorValue) {
                    return rawColorValue / 255;
                }
            }
            Color.redRatio = 0.2126;
            Color.greenRatio = 0.7152;
            Color.blueRatio = 0.0722;
            Color.minChannelLuminenceRatio = .03928;
            Color.minChannelLuminenceDenominator = 12.92;
            Color.luminenceNormalizedAdder = 0.055;
            Color.luminenceDenominator = 1.055;
            Color.luminenceExponent = 2.4;
            Color.WhiteHex = "#ffffff";
            Color.BlackHex = "#000000";
            DbResources.Color = Color;
        })(DbResources = AppOrchard.DbResources || (AppOrchard.DbResources = {}));
    })(AppOrchard = Epic.AppOrchard || (Epic.AppOrchard = {}));
})(Epic || (Epic = {}));
//# sourceMappingURL=DbResources.js.map;